基礎連接代碼
public class JdbcRemoteConnect {
public static void main(String[] args) throws SQLException {
// 1. 加載驅動 (JDBC 4.0+ 可省略, SPI 自動發現)
// Class.forName("com.mysql.cj.jdbc.Driver");
// 2. 構建 URL - 關鍵參數解析
String url = "jdbc:mysql://10.27.104.176:3306/mydatabase?" +
"useSSL=false&" + // 內網可關閉 SSL 減少握手開銷
"serverTimezone=Asia/Shanghai&" + // 時區匹配, 避免時間字段偏移
"characterEncoding=utf-8&" + // 字符集
"allowPublicKeyRetrieval=true&" + // 支持 caching_sha2_password
"autoReconnect=true&" + // 自動重連 (慎用, 推薦連接池管理)
"useUnicode=true&" +
"maxAllowedPacket=64M"; // 大字段支持
// 3. 獲取連接
try (Connection conn = DriverManager.getConnection(url, "root", "mysql");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM apparatus_info")) {
// 4. 處理結果集
while (rs.next()) {
System.out.println("ID: " + rs.getObject(1));
System.out.println("Name: " + rs.getObject(2));
}
} // try-with-resources 自動關閉 rs, stmt, conn
}
}
URL 核心參數詳解
| 參數 | 推薦值 | 作用 |
| useSSL | false (內網) / true (公網) | 加密傳輸,公網必須開啟 |
| serverTimezone | Asia/Shanghai | 解決 DATETIME/TIMESTAMP 時區偏移 |
| characterEncoding | utf-8 / utf8mb4 | 支持 Emoji 等 4 字節字符需 utf8mb4 |
| allowPublicKeyRetrieval | true | MySQL 8.0 默認 caching_sha2_password 需要 |
| rewriteBatchedStatements | true | 批量 INSERT/UPDATE 重寫為多值語句,性能提升 10 倍+ |
| useServerPrepStmts | true | 服務端預編譯,配合 prepareStatement 復用 |
| cachePrepStmts | true | 客戶端緩存 PreparedStatement |
| prepStmtCacheSize | 250 | 緩存語句數量 |
| prepStmtCacheSqlLimit | 2048 | 單條 SQL 最大長度 |
| connectTimeout | 10000 (ms) | 建立連接超時 |
| socketTimeout | 30000 (ms) | 讀寫超時,防止無限阻塞 |
生產環境必上:連接池
com.zaxxer
HikariCP
5.0.1
// 配置示例 (application.yml)
spring:
datasource:
url: jdbc:mysql://10.27.104.176:3306/mydatabase?useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
username: root
password: mysql
hikari:
maximum-pool-size: 20
minimum-idle: 5
idle-timeout: 300000
connection-timeout: 20000
max-lifetime: 1200000
connection-test-query: SELECT 1
pool-name: MyAppPool
常見故障與排查清單
- Communications link failure
- 檢查 IP/端口/防火牆/安全組
- MySQL
bind-address = 0.0.0.0 (非 127.0.0.1)
- 用戶宿主權限:
CREATE USER 'root'@'%' IDENTIFIED BY 'pwd'; GRANT ALL ON *.* TO 'root'@'%';
- Public Key Retrieval is not allowed
- URL 加
allowPublicKeyRetrieval=true 或改用 mysql_native_password
- Timezone 'xxx' is unrecognized
- Data truncation: Incorrect string value
- 連接泄漏 / 池耗盡
- 啟用
connection-timeout、max-lifetime
- 代碼必須
try-with-resources 或 finally 關閉
- 監控
HikariPool-1 - Pool stats 日誌
最佳實踐總結
- ✅ URL 參數顯式全量配置,不依賴默認值
- ✅ 連接池是生產標配,拒絕手動
DriverManager
- ✅
PreparedStatement 防注入 + 性能,批量操作開啟 rewriteBatchedStatements
- ✅ 異常處理:捕獲
SQLException 記錄 SQLState、ErrorCode、SQL 文本
- ✅ 監控指標:活躍連接、等待線程、獲取耗時、泄漏檢測