Class.forName(driverClass).newInstance()DriverManager.getConnection(url, user, pass) 或 getConnection(url, Properties)| 資料庫 | 驅動類別 | JDBC URL 範例 | 備註 |
|---|---|---|---|
| Oracle 8/8i/9i (Thin) | oracle.jdbc.driver.OracleDriver | jdbc:oracle:thin:@localhost:1521:orcl | orcl 為 SID;Thin 驅動純 Java,無需 Client |
| DB2 | com.ibm.db2.jdbc.app.DB2Driver | jdbc:db2://localhost:5000/sample | sample 為資料庫名 |
| SQL Server 7.0/2000 | com.microsoft.jdbc.sqlserver.SQLServerDriver | jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb | Microsoft 官方驅動 |
| Sybase | com.sybase.jdbc.SybDriver | jdbc:sybase:Tds:localhost:5007/myDB | 透過 Properties 傳遞帳密 |
| Informix | com.informix.jdbc.IfxDriver | jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver;user=test;password=test | URL 含伺服器名與認證 |
| MySQL | com.mysql.jdbc.Driver (5.0+) | jdbc:mysql://localhost/myDB?user=root&password=1234&useUnicode=true&characterEncoding=utf8 | 舊驅動 org.gjt.mm.mysql.Driver 已棄用 |
| PostgreSQL | org.postgresql.Driver | jdbc:postgresql://localhost/myDB | 帳密可放 URL 或個別參數 |
| Access (ODBC 橋接) | sun.jdbc.odbc.JdbcOdbcDriver | jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/data/demo.mdb | JDK 8 移除 JDBC-ODBC Bridge,建議改用 UCanAccess |
public class JdbcUtil {
public static Connection getConnection(String driver, String url, String user, String pass)
throws ClassNotFoundException, SQLException {
Class.forName(driver).newInstance();
return DriverManager.getConnection(url, user, pass);
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
try { if (rs != null) rs.close(); } catch (SQLException ignore) {}
try { if (stmt != null) stmt.close(); } catch (SQLException ignore) {}
try { if (conn != null) conn.close(); } catch (SQLException ignore) {}
}
}
mysql-connector-java-5.x.jar,舊 mm.mysql 會報 Communication failure during handshake。useUnicode=true&characterEncoding=utf8 避免中文亂碼。try-with-resources (JDK 7+) 自動關閉 Connection/Statement/ResultSet。掌握各資料庫 JDBC URL 格式與驅動類別,是 Java 後端開發的基本功。搭配連線池與現代持久層框架,能構建高效、穩定的資料存取層。