Skip to content

Instantly share code, notes, and snippets.

@cristofersousa
Created October 5, 2024 13:29
Show Gist options
  • Select an option

  • Save cristofersousa/0687f8fb445bc153e584d99e53fb3d6a to your computer and use it in GitHub Desktop.

Select an option

Save cristofersousa/0687f8fb445bc153e584d99e53fb3d6a to your computer and use it in GitHub Desktop.
package org.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class FabricaConexao {
private static final String URL = "jdbc:mysql://localhost:3306/zoolologicoDB";
private static final String USUARIO = "root";
private static final String SENHA = "";
// Método para obter uma conexão
public static Connection getConexao() throws SQLException {
return DriverManager.getConnection(URL, USUARIO, SENHA);
}
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Driver JDBC do MySQL não encontrado.", e);
}
}
// Método principal para testar a conexão
public static void main(String[] args) {
try (Connection conexao = FabricaConexao.getConexao()) {
System.out.println("Conexão estabelecida com sucesso!");
} catch (SQLException e) {
System.out.println("Erro ao conectar ao banco de dados.");
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment