Class.forName("com.mysql.cj.jdbc.Driver") (JDBC 4.0+ 可省略)DriverManager.getConnection(url, user, pass)Statement / PreparedStatement / CallableStatementResultSet 讀取後必須 close()public class JdbcDemo {
static final String URL = "jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC";
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
// 1. 建立連線 (try-with-resources 自動關閉)
try (Connection conn = DriverManager.getConnection(URL, USER, PASS)) {
// 2. 新增 (PreparedStatement 防 SQL 注入)
String insertSql = "INSERT INTO users(name, email) VALUES(?, ?)";
try (PreparedStatement ps = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, "Alice");
ps.setString(2, "alice@example.com");
int rows = ps.executeUpdate();
System.out.println("新增筆數:" + rows);
// 取得自增主鍵
try (ResultSet keys = ps.getGeneratedKeys()) {
if (keys.next()) System.out.println("生成 ID:" + keys.getLong(1));
}
}
// 3. 查詢
String querySql = "SELECT id, name, email FROM users WHERE id > ?";
try (PreparedStatement ps = conn.prepareStatement(querySql)) {
ps.setInt(1, 0);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.printf("ID:%d Name:%s Email:%s%n",
rs.getLong("id"), rs.getString("name"), rs.getString("email"));
}
}
}
// 4. 交易控制:轉帳範例
conn.setAutoCommit(false); // 開啟交易
try {
updateBalance(conn, 1, -100); // 扣款
updateBalance(conn, 2, 100); // 入帳
conn.commit(); // 提交
System.out.println("轉帳成功");
} catch (Exception e) {
conn.rollback(); // 回滾
System.out.println("轉帳失敗,已回滾:" + e.getMessage());
} finally {
conn.setAutoCommit(true); // 恢復預設
}
} catch (SQLException e) {
e.printStackTrace();
}
}
static void updateBalance(Connection conn, long userId, int amount) throws SQLException {
String sql = "UPDATE users SET balance = balance + ? WHERE id = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, amount);
ps.setLong(2, userId);
ps.executeUpdate();
}
}
}
頻繁建立/關閉連線極其低效。推薦 HikariCP (Spring Boot 預設):
// Maven: com.zaxxer:HikariCP:5.0.1
HikariConfig config = new HikariConfig();
config.setJdbcUrl(URL);
config.setUsername(USER);
config.setPassword(PASS);
config.setMaximumPoolSize(20);
config.setMinimumIdle(5);
DataSource ds = new HikariDataSource(config);
// 使用時:try (Connection conn = ds.getConnection()) { ... }
PreparedStatement 防止 SQL 注入ResultSet、Statement、Connection (try-with-resources)ps.addBatch() + ps.executeBatch()fetchSize 優化大量查詢:stmt.setFetchSize(1000)掌握以上核心,即可在 Java 專案中穩健高效地操作關聯式資料庫。