Advertisement
Guest User

DatabaseConnection()

a guest
Oct 23rd, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. package trabalho;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.SQLException;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8.  
  9.  
  10. /*
  11.  Mudei o nome de 'Connection' pra 'DatabaseConnection' porque o Java tem uma
  12.  classe chamada Connection do pacote 'java.sql' e poderia causar confusão porque
  13.  tu não tava especificando o pacote. Ou seja, não saber se é do Java ou se é a
  14.  tua.
  15.  */
  16. public class DatabaseConnection {
  17.  
  18.     private static final Logger LOG = Logger.getLogger(DatabaseConnection.class.getName());
  19.  
  20.     //static define que existira para todas instancia da classe final define valor nao pode ser alterado
  21.     private static final String USER = "root";
  22.     private static final String SENHA = "vitor2020";
  23.     private static final String URL = "jdbc:mysql://127.0.0.1:3306/java";
  24.     private static final String DRIVER = "com.mysql.jdbc.Driver";
  25.  
  26.     private DatabaseConnection() {}
  27.  
  28.     private static class DatabaseConnectionHolder {
  29.  
  30.         private static final DatabaseConnection INSTANCE = new DatabaseConnection();
  31.     }
  32.  
  33.     public static DatabaseConnection getInstance() {
  34.         return DatabaseConnectionHolder.INSTANCE;
  35.     }
  36.  
  37.     public Connection getConnection() {
  38.         Connection conn = null;
  39.         try {
  40.             Class.forName(DRIVER);
  41.             conn = DriverManager.getConnection(URL, USER, SENHA);
  42.         } catch (ClassNotFoundException | SQLException ex) {
  43.             LOG.log(Level.SEVERE, null, ex);
  44.         }
  45.         return conn;
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement