JDBC (Java Database Connectivity) 是 Java 操作關係數據庫的基礎 API。本文以 MySQL 為例,演示使用 `Statement` 執行 INSERT 語句的標準流程,重點講解資源獲取、執行、關閉的正確姿勢。
import java.sql.*;
import java.io.InputStream;
import java.util.Properties;
public class JdbcInsertDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 1. 讀取配置文件
Properties props = loadProps("jdbc.properties");
String driver = props.getProperty("driver");
String url = props.getProperty("jdbcUrl");
String user = props.getProperty("user");
String pwd = props.getProperty("password");
// 2. 加載驅動
Class.forName(driver);
// 3. 獲取連接
conn = DriverManager.getConnection(url, user, pwd);
// 4. 創建 Statement
stmt = conn.createStatement();
// 5. 準備 SQL
String sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) " +
"VALUES ('李小龍', 'long@live.com', '1940-11-27')";
// 6. 執行插入
int affected = stmt.executeUpdate(sql);
System.out.println("受影響行數: " + affected + (affected > 0 ? " 插入成功" : " 插入失敗"));
} catch (Exception e) {
e.printStackTrace();
} finally {
// 7. 關閉資源(逆序)
closeQuietly(stmt);
closeQuietly(conn);
}
}
private static Properties loadProps(String fileName) throws Exception {
try (InputStream is = JdbcInsertDemo.class.getClassLoader().getResourceAsStream(fileName)) {
Properties p = new Properties();
p.load(is);
return p;
}
}
private static void closeQuietly(AutoCloseable c) {
if (c != null) try { c.close(); } catch (Exception ignored) {}
}
}
driver=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC user=root password=root
CREATE TABLE customers (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50),
EMAIL VARCHAR(100),
BIRTH DATE
);
| 特性 | Statement | PreparedStatement |
|---|---|---|
| SQL 注入防護 | 無,需手動轉義 | 參數佔位符 `?` 自動防注入 |
| 性能 | 每次編譯 | 預編譯,批量執行極快 |
| 適用場景 | 簡單、無參數、極少執行 | 所有生產環境業務 SQL |
生產代碼請務必使用 PreparedStatement!
// 錯誤示範:若 stmt.close() 拋異常,conn 永不關閉
stmt.close();
conn.close();
// 正確模式:分別 try-catch 或使用 try-with-resources (Java 7+)
try (Connection conn = DriverManager.getConnection(...);
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, "value");
ps.executeUpdate();
} // 自動關閉,即使拋異常也安全
將數據庫連接信息外部化到 `.properties` 文件,便於多環境(開發/測試/生產)切換,避免硬編碼洩露密碼。
String sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) VALUES (?, ?, ?)";
try (Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, "Bruce Lee");
ps.setString(2, "bruce@lee.com");
ps.setDate(3, Date.valueOf("1940-11-27"));
ps.executeUpdate();
}
JDBC 基礎雖簡單,但資源管理、SQL 注入防護、連接池複用等工程化細節決定系統穩定性。初學者應從 `PreparedStatement` + `try-with-resources` 起步,養成良好習慣。