Guest User

Untitled

a guest
Mar 6th, 2016
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package Modelo;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.SQLException;
  6.  
  7. public class Database {
  8.     private String db = "";
  9.     private String user = "";
  10.     private String password = "";
  11.     private String url = "";
  12.     private Connection conn = null;
  13.    
  14.     public void conectar(){
  15.         try{
  16.             Class.forName("com.mysql.jdbc.Driver");
  17.             conn = DriverManager.getConnection(this.url, this.user , this.password);    
  18.             System.out.println("Conexion MySQL realizada con exito.");
  19.         }catch(SQLException e){
  20.             System.out.println("Conexion NO realizada con exito por error de SQL.");
  21.             e.printStackTrace();
  22.         }catch(ClassNotFoundException e){
  23.             System.out.println("Conexion NO realizada con exito por error de Class.");
  24.             e.printStackTrace();
  25.         }
  26.     }
  27.  
  28.     //Aplicamos el funcionamiento de Singleton para evitar crear un segundo objeto de Conexión mediante la reutilización del ya existente
  29.     public Connection getConexion() {
  30.         try{
  31.             if(this.conn.isClosed()){
  32.                 Class.forName("com.mysql.jdbc.Driver");
  33.                 this.conn = DriverManager.getConnection(this.url, this.user , this.password);    
  34.             }
  35.         }catch(SQLException | ClassNotFoundException e){
  36.             e.printStackTrace();
  37.         }
  38.         return this.conn;
  39.     }
  40.    
  41.     public void setDatabase(String db){
  42.         this.db = db;
  43.     }
  44.    
  45.     public void setUser(String user){
  46.         this.user = user;
  47.     }
  48.    
  49.     public void setPassword(String password){
  50.         this.password = password;
  51.     }
  52.    
  53.     public void setURL(String ip, String puerto){
  54.         this.url = "jdbc:mysql://" + ip + ":" + puerto + "/" + db;
  55.     }
  56. }
Add Comment
Please, Sign In to add comment