Java 應用程式透過 JDBC API 與關聯式資料庫互動。本文詳細說明兩種連接方案:JDBC-ODBC 橋接器(舊版適用)與原生 JDBC 驅動(現代標準),含設定步驟、程式碼範例與最佳實踐。
標準三層架構:
原理:Java → JDBC-ODBC Bridge → ODBC 驅動 → DBMS
Windows ODBC 設定步驟:
public static Connection connectViaJdbcOdbc(String dsn, String user, String pwd) {
Connection conn = null;
try {
// 1. 載入橋接驅動
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// 2. 建立連接
String url = "jdbc:odbc:" + dsn;
conn = DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return conn;
}
// 使用範例
Connection conn = connectViaJdbcOdbc("myDSN", "admin", "1234");
if (conn != null) {
System.out.println("連接成功");
conn.close();
}
核心步驟:
| 資料庫 | 驅動類別 | URL 格式 | 預設埠口 |
|---|---|---|---|
| MySQL | com.mysql.cj.jdbc.Driver | jdbc:mysql://host:port/db?useSSL=false&serverTimezone=UTC | 3306 |
| PostgreSQL | org.postgresql.Driver | jdbc:postgresql://host:port/db | 5432 |
| Oracle | oracle.jdbc.OracleDriver | jdbc:oracle:thin:@host:port:sid | 1521 |
| SQL Server | com.microsoft.sqlserver.jdbc.SQLServerDriver | jdbc:sqlserver://host:port;databaseName=db | 1433 |
public class JdbcUtil {
// 靜態區塊載入驅動(僅執行一次)
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // 依專案實際資料庫調整
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError("找不到 JDBC 驅動: " + e.getMessage());
}
}
public static Connection getConnection(String url, String user, String pwd)
throws SQLException {
return DriverManager.getConnection(url, user, pwd);
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
try { if (rs != null) rs.close(); } catch (SQLException ignored) {}
try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {}
try { if (conn != null) conn.close(); } catch (SQLException ignored) {}
}
}
頻繁建立/關閉連接效能極差,必須使用連接池:
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC");
config.setUsername("root");
config.setPassword("password");
config.setMaximumPoolSize(20);
config.setMinimumIdle(5);
config.setConnectionTimeout(30000);
config.setIdleTimeout(600000);
config.setMaxLifetime(1800000);
HikariDataSource ds = new HikariDataSource(config);
// 使用時:Connection conn = ds.getConnection();
PreparedStatement 防 SQL 注入