驅動部署三種方式 (擇一)
方式 1:專案庫 (Maven/Gradle 推薦)
<!-- Maven -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId> <!-- 8.0+ -->
<version>8.2.0</version>
</dependency>
<!-- Gradle -->
implementation 'com.mysql:mysql-connector-j:8.2.0'
方式 2:JRE 擴充目錄 (舊版通用)
# 複製 jar 到
%JAVA_HOME%\jre\lib\ext\mysql-connector-java-5.1.49.jar
# 或 JDK 9+ 模組路徑
方式 3:Web 應用 (WEB-INF/lib)
# 放入專案
src/main/webapp/WEB-INF/lib/mysql-connector-j-8.2.0.jar
# 或 Tomcat 共用
$CATALINA_HOME/lib/mysql-connector-j-8.2.0.jar
標準連線程式碼 (JDBC 4.0+ 自動載入驅動)
import java.sql.*;
public class MySQLDemo {
static final String URL = "jdbc:mysql://localhost:3306/sample_db?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement()) {
// 查詢
ResultSet rs = stmt.executeQuery("SELECT id, name FROM test");
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
// 更新
int rows = stmt.executeUpdate("INSERT INTO test (name) VALUES ('JDBC')");
System.out.println("Inserted rows: " + rows);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
關鍵連線參數 (MySQL 8.0+)
| 參數 | 建議值 | 說明 |
| useSSL | false | 本地開發關閉 SSL |
| serverTimezone | UTC / Asia/Taipei | 避免時區警告 |
| characterEncoding | utf8 / utf8mb4 | 中文編碼 |
| allowPublicKeyRetrieval | true | 支援 caching_sha2_password |
| rewriteBatchedStatements | true | 批次執行優化 |
常見錯誤排查
| 錯誤 | 原因 | 解決 |
| ClassNotFoundException: com.mysql.jdbc.Driver | 驅動未在 Classpath / 驅動類名舊 (5.x) | Maven 依賴 / 8.0 用 com.mysql.cj.jdbc.Driver |
| Communications link failure | IP/埠/防火牆/MySQL bind-address | 檢查 3306、my.cnf bind-address=0.0.0.0 |
| Public Key Retrieval is not allowed | 認證插件 caching_sha2_password | 加 allowPublicKeyRetrieval=true |
| Zero date value prohibited | 資料含 '0000-00-00' | 連線加 zeroDateTimeBehavior=CONVERT_TO_NULL |