JDBC 驅動是 Java 連接 MySQL 的橋梁。本文覆蓋官網下載、手動導入 JAR、Maven 坐標、Eclipse Build Path 配置、模塊化 (JPMS) 宣告、常見版本兼容性陷阱與驗證代碼。
MySQL Connector/J → 選擇 Platform Independent → 下載 mysql-connector-j-8.x.x.zip (8.0+) 或 mysql-connector-java-5.1.x.zip (5.1)。解壓獲取 mysql-connector-j-8.x.x.jar。
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version> <!-- 或 5.1.49 -->
</dependency>
Maven 會自動下載到本地倉庫並加入 Classpath,無需手動操作。
module com.example.app {
requires com.mysql.cj.jdbc; -- 自動模塊名
requires java.sql;
requires java.logging;
}
| 版本 | 驅動類 | URL 前綴 | 備註 |
|---|---|---|---|
| 8.0+ (Connector/J 8.x) | com.mysql.cj.jdbc.Driver | jdbc:mysql:// | 預設 SSL、時區需顯式配置 |
| 5.1 (Connector/J 5.1) | com.mysql.jdbc.Driver | jdbc:mysql:// | 已停止維護,建議升級 |
import java.sql.*;
public class JdbcTest {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test_db?" +
"useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
String user = "root";
String pass = "your_password";
try (Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT VERSION()")) {
if (rs.next()) {
System.out.println("MySQL Version: " + rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 錯誤 | 原因 | 解決 |
|---|---|---|
| ClassNotFoundException | JAR 不在 Classpath | Maven 依賴 / Eclipse Build Path / java -cp |
| Communications link failure | IP/端口錯、防火牆、bind-address | telnet host 3306、my.cnf bind-address=0.0.0.0 |
| Public Key Retrieval is not allowed | 8.0 caching_sha2_password | URL 加 allowPublicKeyRetrieval=true 或用 mysql_native_password |
| Server timezone value '...' unrecognized | 時區不匹配 | URL 加 serverTimezone=Asia/Shanghai 或 UTC |
| SSLHandshakeException | 驅動預設 SSL、服務端無憑證 | URL 加 useSSL=false (開發) 或配置憑證 (生產) |
rewriteBatchedStatements=true 批次優化。JDBC 驅動只是「翻譯官」,連接池才是「管理者」。現代 Java 開發請直接implementation 'com.zaxxer:HikariCP:5.x'+implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.x',專注業務邏輯而非底層連接管理。