Class.forName("driver.class.Name"); // JDK 6+ 可省略
String url = "jdbc:subprotocol://host:port/db?params";
String user = "username", pwd = "password";
Connection conn = DriverManager.getConnection(url, user, pwd);
| 數據庫 | 驅動類 (JDBC 4.2+) | URL 格式 | 關鍵參數說明 |
|---|---|---|---|
| MySQL 5.7/8.0 | com.mysql.cj.jdbc.Driver |
jdbc:mysql://host:3306/dbname?useSSL=false&serverTimezone=UTC&characterEncoding=utf8&allowPublicKeyRetrieval=true |
useSSL、serverTimezone (8.0 必填)、characterEncoding、allowPublicKeyRetrieval (caching_sha2_password) |
| PostgreSQL | org.postgresql.Driver |
jdbc:postgresql://host:5432/dbname?currentSchema=public&ApplicationName=myApp |
currentSchema、ApplicationName、reWriteBatchedInserts=true (批量優化) |
| Oracle 12c/19c/21c | oracle.jdbc.OracleDriver |
jdbc:oracle:thin:@//host:1521/service_name (Easy Connect)或 jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=host)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=svc))) |
SID vs Service Name、oracle.net.CONNECT_TIMEOUT、defaultRowPrefetch |
| SQL Server | com.microsoft.sqlserver.jdbc.SQLServerDriver |
jdbc:sqlserver://host:1433;databaseName=db;encrypt=true;trustServerCertificate=false |
encrypt、trustServerCertificate、integratedSecurity (Windows 認證)、applicationName |
| DB2 | com.ibm.db2.jcc.DB2Driver |
jdbc:db2://host:50000/dbname:driverType=4;retrieveMessagesFromServerOnGetMessage=true; |
driverType=4 (Type 4 純 Java)、currentSchema |
| Sybase ASE | com.sybase.jdbc4.jdbc.SybDriver |
jdbc:sybase:Tds:host:5000/dbname?CHARSET=utf8 |
CHARSET、LOB_CACHE_SIZE |
| Informix | com.informix.jdbc.IfxDriver |
jdbc:informix-sqli://host:1533/dbname:INFORMIXSERVER=server_name;user=user;password=pwd |
INFORMIXSERVER、IFX_LOCK_MODE_WAIT |
| H2 (嵌入式/服務端) | org.h2.Driver |
jdbc:h2:~/test;AUTO_SERVER=TRUE;MVCC=TRUE (嵌入)jdbc:h2:tcp://host:9092/~/test (服務端) |
AUTO_SERVER、MVCC、DB_CLOSE_DELAY=-1 |
| SQLite | org.sqlite.JDBC |
jdbc:sqlite:/path/to/dbfile.db |
文件路徑、journal_mode=WAL、busy_timeout=5000 |
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC");
config.setUsername("user");
config.setPassword("pwd");
config.setDriverClassName("com.mysql.cj.jdbc.Driver"); // 可選
config.setMaximumPoolSize(20);
config.setMinimumIdle(5);
config.setConnectionTimeout(30000);
config.setIdleTimeout(600000);
config.setMaxLifetime(1800000);
config.setConnectionTestQuery("SELECT 1"); // 或依賴 JDBC 4 isValid()
config.setPoolName("MyApp-Pool");
DataSource ds = new HikariDataSource(config);
user@'%'、Oracle tnsnames.ora)useSSL、encrypt、憑證信任rewriteBatchedStatements=true 批量重寫、cachePrepStmts=true、prepStmtCacheSize=250、prepStmtCacheSqlLimit=2048reWriteBatchedInserts=true、preferQueryMode=simpledefaultRowPrefetch=100、useFetchSizeWithLongColumn=trueselectMethod=cursor (大結果集流式)、sendStringParametersAsUnicode=false (非 Unicode 列性能)收藏此表,新項目接入新數據庫時複製修改即可,告別百度複製粘貼出錯的痛苦。