Advertisement
LucSouza

Untitled

Apr 21st, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. package br.com.ConexaoBanco;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.SQLException;
  6.  
  7. public class ConexaoMySQL {
  8.  
  9. private static String usuario="root@localhost";
  10. private static String senha="naosei123";
  11. private static String banco="test";
  12. private static String ip="localhost:3306";
  13. private static String driver="com.mysql.cj.jdbc.Driver";
  14. private static Connection conexao = null;
  15.  
  16. //padrao singleton
  17.  
  18. public static Connection getConnection() {
  19. System.out.println(">>Conectando ao banco");
  20. try {
  21. Class.forName(driver);
  22. // return DriverManager.getConnection ("jdbc:mysql//localhost:3306/test","root","naosei123"); } }
  23.  
  24.  
  25. if(conexao==null || conexao.isClosed()){
  26. conexao=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","naosei123");
  27. }
  28.  
  29.  
  30.  
  31. return conexao;
  32. }catch (ClassNotFoundException e) {
  33. System.out.println("da");
  34. throw new RuntimeException(e);
  35. }catch (SQLException e) {
  36.  
  37. closeConnection();
  38. throw new RuntimeException(e);
  39. }
  40.  
  41. }
  42.  
  43. public static void closeConnection(){
  44. try{
  45. if(conexao!=null && !conexao.isClosed()){
  46. conexao.close();
  47. System.out.println(">>Conexao encerrada com sucesso");
  48. }
  49. }catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }
  53.  
  54.  
  55.  
  56. public static void main(String[] args) {
  57. System.out.println("conexao: "+getConnection());
  58. System.out.println("conexao: "+getConnection());
  59. System.out.println("conexao: "+getConnection());
  60. }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement