try {
Class.forName("com.mysql.cj.jdbc.Driver"); // MySQL 8.0+ 驅動類
} catch (ClassNotFoundException e) {
throw new RuntimeException("找不到驅動類", e);
}
驅動加載成功後會自動註冊到 DriverManager。
String url = "jdbc:mysql://localhost:3306/mydb?" +
"useUnicode=true&characterEncoding=utf8&" +
"useSSL=false&serverTimezone=Asia/Shanghai&" +
"allowPublicKeyRetrieval=true";
| 參數 | 說明 | |
|---|---|---|
| useUnicode | 使用 Unicode 字符集 | |
| characterEncoding | 字符編碼,推薦 utf8/utf8mb4 | |
| useSSL | 是否使用 SSL,開發環境建議 false | |
| serverTimezone | 服務器時區,避免時間差報錯 | |
| allowPublicKeyRetrieval | MySQL 8.0 密碼插件需要 |
| 類型 | 適用場景 | 創建方式 |
|---|---|---|
| Statement | 靜態 SQL,無參數 | conn.createStatement() |
| PreparedStatement | 參數化 SQL,防注入,預編譯 | conn.prepareStatement(sql) |
| CallableStatement | 調用存儲過程 | conn.prepareCall("{call proc(?,?)}") |
// 查詢 - executeQuery 返回 ResultSet
String sql = "SELECT id, name, age FROM users WHERE age > ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 18);
ResultSet rs = ps.executeQuery();
// 更新 - executeUpdate 返回影響行數
String insertSql = "INSERT INTO users(name, age) VALUES (?, ?)";
PreparedStatement ps2 = conn.prepareStatement(insertSql);
ps2.setString(1, "張三");
ps2.setInt(2, 25);
int rows = ps2.executeUpdate();
while (rs.next()) {
// 列索引從 1 開始,或使用列名
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.printf("ID: %d, Name: %s, Age: %d%n", id, name, age);
}
// Java 7+ try-with-resources 自動關閉 (推薦)
try (Connection conn = DriverManager.getConnection(url, user, pwd);
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
// 業務邏輯
} catch (SQLException e) {
e.printStackTrace();
}
// 手動關閉模板
finally {
closeQuietly(rs);
closeQuietly(ps);
closeQuietly(conn);
}
void closeQuietly(AutoCloseable closeable) {
if (closeable != null) {
try { closeable.close(); } catch (Exception ignored) {}
}
}
public class JdbcDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
String user = "root";
String pwd = "root";
String sql = "SELECT * FROM users WHERE age > ?";
try (Connection conn = DriverManager.getConnection(url, user, pwd);
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 20);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " | " +
rs.getString("name") + " | " +
rs.getInt("age"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
serverTimezone=Asia/ShanghaiuseSSL=false 或配置憑證allowPublicKeyRetrieval=truecharacterEncoding=utf8 且數據庫表字符集一致生產環境必須使用連接池(HikariCP、Druid、DBCP2),避免頻繁創建銷毀連接開銷:
// HikariCP 示例
HikariConfig config = new HikariConfig();
config.setJdbcUrl(url);
config.setUsername(user);
config.setPassword(pwd);
config.setMaximumPoolSize(20);
DataSource ds = new HikariDataSource(config);
// 使用
try (Connection conn = ds.getConnection()) { ... }
掌握 JDBC 基礎操作,配合連接池與參數化查詢,是 Java 後端開發的核心必備技能。