Advertisement
Guest User

Untitled

a guest
Jun 8th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. package conectabasedato;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.util.logging.Level;
  9. import java.util.logging.Logger;
  10.  
  11. /**
  12. *
  13. * @author Javier
  14. */
  15.  
  16. public class Conectar {
  17.  
  18. //primero es abrir la coneccion
  19. public Connection abrirConexion() throws SQLException{
  20. String user="root";
  21. String password="";
  22.  
  23. String protocolo="jdbc:mysql://";
  24. String server="localhost";
  25. String puerto="3306";
  26. String bd="ejemplo";
  27. String url=protocolo+server+":"+puerto+"/"+bd;
  28. Connection cnx= null;
  29.  
  30. try {
  31. Class.forName("com.mysql.jdbc.Driver");
  32. cnx=DriverManager.getConnection(url, user, password);
  33.  
  34. } catch (ClassNotFoundException ex) {
  35. Logger.getLogger(Conectar.class.getName()).log(Level.SEVERE, null, ex);
  36. System.out.println("Error de driver");
  37. }
  38.  
  39. return cnx;
  40.  
  41. }
  42.  
  43. public void cerrarConexion(Connection cnx){
  44.  
  45. try {
  46. cnx.close();
  47. } catch (SQLException ex) {
  48. Logger.getLogger(Conectar.class.getName()).log(Level.SEVERE, null, ex);
  49. }
  50. }
  51.  
  52. public int actualizar(Connection cnx, String sql){
  53. int resultado=0;
  54. try {
  55. Statement st= cnx.createStatement();
  56. resultado=st.executeUpdate(sql);
  57.  
  58. } catch (SQLException ex) {
  59. Logger.getLogger(Conectar.class.getName()).log(Level.SEVERE, null, ex);
  60.  
  61. }
  62. return resultado;
  63. }
  64.  
  65. public ResultSet consulta(Connection cnx, String sql){
  66.  
  67. ResultSet resultado = null;
  68.  
  69. try {
  70.  
  71. Statement st= cnx.createStatement();
  72. resultado=st.executeQuery(sql);
  73.  
  74. } catch (SQLException ex) {
  75. Logger.getLogger(Conectar.class.getName()).log(Level.SEVERE, null, ex);
  76. }
  77.  
  78. return resultado;
  79.  
  80. }
  81.  
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement