JDBC (Java Database Connectivity) 是用於執行 SQL 陳述式的 Java API,提供統一介面訪問多種關聯式資料庫。由一組 Java 類與介面組成,讓開發者能輕鬆發送 SQL 語句,構建資料庫應用。
Class.forName("com.mysql.jdbc.Driver");
// 或
new com.mysql.jdbc.Driver();

jdbc:mysql://host:port/dbname?param1=value1¶m2=value2

Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ...");

| 參數 | 說明 | 建議值 |
|---|---|---|
useUnicode | 使用 Unicode 字元集 | true |
characterEncoding | 字元編碼(配合 useUnicode) | UTF-8 或 GBK |
autoReconnect | 自動重連(不推薦生產環境) | false |
failOverReadOnly | 故障轉移後是否唯讀 | true |
maxReconnects | 最大重連嘗試次數 | 3 |
connectTimeout | 連接超時(毫秒) | 30000 |
socketTimeout | Socket 讀寫超時(毫秒) | 30000 |
useSSL | 是否使用 SSL | false(內網) |
serverTimezone | 伺服器時區(8.0+ 必填) | Asia/Shanghai 或 GMT%2B8 |
allowPublicKeyRetrieval | 允許獲取公鑰(8.0+ caching_sha2_password) | true |
import java.sql.*;
public class MysqlDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/javademo?" +
"user=root&password=root&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("成功載入 MySQL 驅動");
conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
// 建表
String sql = "CREATE TABLE student (id CHAR(20), name VARCHAR(20), PRIMARY KEY(id))";
int result = stmt.executeUpdate(sql);
if (result != -1) System.out.println("建表成功");
// 插入
stmt.executeUpdate("INSERT INTO student VALUES('2012001','張三')");
stmt.executeUpdate("INSERT INTO student VALUES('2012002','李四')");
// 查詢
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
System.out.println("學號\t姓名");
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2));
}
} catch (SQLException e) {
System.out.println("MySQL 操作錯誤"); e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) try { conn.close(); } catch (SQLException ignored) {}
}
}
}
注意: MySQL 8.0+ 驅動類名為com.mysql.cj.jdbc.Driver,舊版為com.mysql.jdbc.Driver。務必加上serverTimezone避免時區報錯。