File → New → Java Project,項目名 JDBCDemo。mysql-connector-java-x.x.x.jar。Build Path → Configure Build Path → Libraries → Classpath → Add External JARs → 選中 JAR → Apply and Close。lib 目錄放入 JAR,右鍵 JAR → Build Path → Add to Build Path。import java.sql.*;
public class MySQLConn {
public static void main(String[] args) {
// 1. 加載驅動 (JDBC 4.0+ 可省略,保留兼容舊版)
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // 8.0+ 驅動類名
System.out.println("Driver loaded");
} catch (ClassNotFoundException e) {
System.err.println("Driver not found!");
e.printStackTrace();
return;
}
// 2. 建立連接
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&characterEncoding=utf8mb4";
String user = "root";
String pwd = "123";
try (Connection conn = DriverManager.getConnection(url, user, pwd)) {
System.out.println("Connected!");
// 3. 執行查詢
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM user")) {
while (rs.next()) {
System.out.println("name: " + rs.getString("name"));
}
}
} catch (SQLException e) {
System.err.println("SQL Error: " + e.getMessage());
e.printStackTrace();
}
}
}
jdbc:mysql://[host][:port]/[database][?properties]
jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&characterEncoding=utf8mb4&allowPublicKeyRetrieval=true
| 參數 | 推薦值 | 說明 |
|---|---|---|
useSSL | false | 本地/內網開發關閉 SSL,減少握手開銷 |
serverTimezone | UTC 或 Asia/Shanghai | 避免 CST 歧義導致時間偏移 |
characterEncoding | utf8mb4 | 統一字符集,防止中文亂碼 |
allowPublicKeyRetrieval | true | 8.0+ caching_sha2_password 需獲取公鑰 |
autoReconnect | true | 舊版參數,新版建議用連接池管理重連 |
rewriteBatchedStatements | true | 批量 INSERT 重寫為多值 INSERT,大幅提速 |
Connection、Statement、ResultSet 實現 AutoCloseable,自動關閉,防洩漏。ClassNotFoundException (驅動缺失) / SQLException (連接/執行錯誤)。e.getSQLState()、e.getErrorCode()、e.getMessage()。String sql = "INSERT INTO user (username, email) VALUES (?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
for (int i = 0; i < 1000; i++) {
ps.setString(1, "user" + i);
ps.setString(2, "user" + i + "@ex.com");
ps.addBatch();
}
int[] counts = ps.executeBatch(); // 批量執行
System.out.println("Inserted: " + counts.length);
}
應用代碼 (JDBC API)
│
▼
JDBC 驅動 (mysql-connector-j) ← 實現標準接口,轉換為 MySQL 協議
│
▼
MySQL Server (TCP 3306 / Unix Socket)
掌握這三層,排查問題時能快速定位:代碼邏輯 → 驅動版本/參數 → Server 配置/權限/網絡。