Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. public class Conexion {
  2.  
  3. private Connection con;
  4. private final String driver = "com.mysql.cj.jdbc.Driver";
  5. private final String usuario = "TestBD";
  6. private final String contrasena = "pass";
  7. private final String urlBaseDatos = "jdbc:mysql://localhost:3306/TestBD?serverTimezone=UTC";
  8.  
  9. private static Conexion conexion;
  10.  
  11. private Conexion(){}
  12.  
  13. public static Conexion getInstance() throws SQLException{
  14. if(conexion == null){
  15. conexion = new Conexion();
  16. }
  17. conexion.conectar();
  18. return conexion;
  19. }
  20.  
  21. private void conectar() throws SQLException{
  22. if (con == null || con.isClosed()) {
  23. try {
  24. Class.forName(driver);
  25. } catch (ClassNotFoundException ex) {
  26. Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
  27. }
  28. con = DriverManager.getConnection(urlBaseDatos, usuario, contrasena);
  29. }
  30. }
  31.  
  32. public boolean existeConexion() throws SQLException{
  33. return con != null && !con.isClosed();
  34. }
  35.  
  36. public Connection getCon() {
  37. return con;
  38. }
  39. }
  40.  
  41. public class TestConexion {
  42. public static void main(String[] args){
  43. try {
  44. if(Conexion.getInstance().existeConexion()){
  45. System.out.println("Conexión Establecida");
  46. }
  47. } catch (SQLException ex) {
  48. Logger.getLogger(TestConexion.class.getName()).log(Level.SEVERE, null, ex);
  49. System.out.println("Error al Establecer la Conexión");
  50. }
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement