Advertisement
eliasbring

Sistemas-Notas/br.elias.alunos.conexao/FabricaConexao

Sep 30th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.40 KB | None | 0 0
  1. package br.elias.alunos.conexao;
  2.  
  3.  
  4. import br.elias.alunos.exception.ErroSistema;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8.  
  9. /**
  10.  *
  11.  * @author elias
  12.  */
  13. public class FabricaConexao {
  14.        
  15.     private static Connection conexao;
  16.     private static final String URL_CONEXAO = "jdbc:mysql://localhost/sistema-alunos";
  17.     private static final String USUARIO = "root";
  18.     private static final String SENHA = "br354895";
  19.  
  20.     public static Connection getConexao() throws ErroSistema {
  21.         if(conexao == null){
  22.             try {
  23.                 Class.forName("com.mysql.jdbc.Driver");
  24.                 conexao = DriverManager.getConnection(URL_CONEXAO, USUARIO, SENHA);
  25.             } catch (SQLException ex) {
  26.                 throw new ErroSistema("Não foi possível conectar ao banco de dados!", ex);
  27.             } catch (ClassNotFoundException ex) {
  28.                 throw new ErroSistema("O driver do banco de dados não foi encontrado!", ex);
  29.             }
  30.         }
  31.         return conexao;
  32.     }
  33.    
  34.     public static void fecharConexao() throws ErroSistema{
  35.         if(conexao != null){
  36.             try {
  37.                 conexao.close();
  38.                 conexao = null;
  39.             } catch (SQLException ex) {
  40.                 throw new ErroSistema("Erro ao fechar conexão com o banco de dados!", ex);
  41.             }
  42.         }
  43.     }
  44.    
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement