O Connection Factory Java
Por: Andre Ribeiro • 21/2/2020 • Trabalho acadêmico • 488 Palavras (2 Páginas) • 221 Visualizações
package util;
import java.sql.*;
public class ConnectionFactory {
private static ConnectionFactory connectionFactory; // Objeto de conexão
public static ConnectionFactory getInstance() { // Verifica se há uma conexão e a retorna. Caso não, inicia uma nova
// conexão
if (connectionFactory == null) {
connectionFactory = new ConnectionFactory();
}
return connectionFactory;
}
public static Connection getConnection() throws Exception {
try {
String url = "xxxxxxxxxx";
String login = "xxxxxxxx";
String senha = "xxxxxxx";
return DriverManager.getConnection(url, login, senha);
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
public static void closeConnection(Connection conn, Statement stmt, ResultSet rs) throws Exception {
close(conn, stmt, rs);
}
public static void closeConnection(Connection conn, Statement stmt) throws Exception {
close(conn, stmt, null);
}
public static void closeConnection(Connection conn) throws Exception {
close(conn, null, null);
}
private static void close(Connection conn, Statement stmt, ResultSet rs) throws Exception {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
}
...