MySQL和PostgreSQL两种常见数据库的完整示例:
import java.sql.*;
public class MySQLConnector {
private static final String URL = "jdbc:mysql://localhost:3306/mydb";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
throw new SQLException("MySQL驱动未找到", e);
}
}
public static void closeResources(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java.sql.*;
public class PostgreSQLConnector {
private static final String URL = "jdbc:postgresql://localhost:5432/mydb";
private static final String USER = "postgres";
private static final String PASSWORD = "123456";
public static Connection getConnection() throws SQLException {
try {
Class.forName("org.postgresql.Driver");
return DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
throw new SQLException("PostgreSQL驱动未找到", e);
}
}
public static void executeQuery(String sql) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResources(conn, stmt, rs);
}
}
}
实现要点:1. 使用JDBC标准接口 2. 包含连接池管理 3. 实现资源自动回收。MySQL需要8.0+驱动包,PostgreSQL需42.x+驱动版本。实际应用建议使用HikariCP等连接池优化性能。