JuanAlves73

ConexaoBD

Nov 24th, 2018
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. package livraria;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.SQLException;
  6.  
  7. public class ConexaoBD {
  8.     // Essa primeira parte é feita para definir as informações do banco
  9.     public Connection connection = null;
  10.     private final String DRIVER = "com.mysql.jdbc.Driver"; //Driver JDBC
  11.     private final String DBNAME = "livraria"; //Nome do banco de dados
  12.     private final String URL = "jdbc:mysql://localhost:3306/"+DBNAME+"?useTimezone=true&serverTimezone=UTC";
  13.     private final String LOGIN = "root"; //Login padrão
  14.     private final String SENHA = "Juancl333"; //Senha padrão
  15.    
  16.     /* Vai ser criada duas funções para podermos usar no JFRAME
  17.         O getConnection para realizar a conexão
  18.         e o close para fechar a conexão
  19.     */
  20.    
  21.     public boolean getConnection(){ /*Ele é boolean pois iremos utilizar isso a nosso favor
  22.                                     no JFrame*/
  23.                                        
  24.         try{
  25.             Class.forName(DRIVER);    
  26.             connection = DriverManager.getConnection(URL, LOGIN, SENHA);
  27.             System.out.println("Conectou");
  28.             return true;    // Quando a conexão é feita, ele retorna true
  29.         }catch(ClassNotFoundException erro){
  30.             System.out.println("Driver não encontrado!\n"+erro.toString());
  31.             return false;    // Quando a conexão é malsucedida, ele retorna false
  32.         }catch(SQLException erro){
  33.             System.out.println("Falha ao conectar!\n"+erro.toString());
  34.             return false;    
  35.         }
  36.     }
  37.    
  38.     public void close(){
  39.         try{
  40.             connection.close();
  41.             System.out.println("Desconectou");
  42.         }catch(SQLException erro){
  43.            
  44.         }
  45.     }
  46.    
  47. }
Add Comment
Please, Sign In to add comment