JDBC 核心三步曲
- 建立數據庫連接
- 發送 SQL 語句
- 處理結果集
完整代碼示例
public class JdbcDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. 加載驅動
Class.forName("com.mysql.jdbc.Driver");
// 2. 獲取連接
String url = "jdbc:mysql://localhost:3306/jdbc";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 3. 創建 Statement
stmt = conn.createStatement();
// 4. 執行 DDL:創建表
String sql = "CREATE TABLE Student (id CHAR(9) PRIMARY KEY, name CHAR(9) UNIQUE)";
stmt.execute(sql);
// 5. 執行 DML:插入數據
sql = "INSERT INTO Student (id, name) VALUES ('0001', 'zhangsan')";
stmt.executeUpdate(sql);
// 6. 執行 DQL:查詢數據
sql = "SELECT * FROM Student";
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("id: " + rs.getString("id"));
System.out.println("name: " + rs.getString("name"));
}
// 7. 執行 DML:刪除數據
sql = "DELETE FROM Student WHERE id='0001'";
stmt.executeUpdate(sql);
// 8. 執行 DDL:刪除表
sql = "DROP TABLE Student";
stmt.execute(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 9. 關閉資源(逆序)
closeQuietly(rs);
closeQuietly(stmt);
closeQuietly(conn);
}
}
private static void closeQuietly(AutoCloseable closeable) {
if (closeable != null) {
try { closeable.close(); } catch (Exception ignored) {}
}
}
}
關鍵 API 解析
| 方法 | 用途 | 返回值 |
| execute(String sql) | 執行任意 SQL(DDL/DML/DQL) | boolean(是否有 ResultSet) |
| executeQuery(String sql) | 執行查詢 | ResultSet |
| executeUpdate(String sql) | 執行增刪改 | int(影響行數) |
資源管理最佳實踐
- 關閉順序:ResultSet → Statement → Connection(逆創建順序)
- 異常安全:使用 try-with-resources (JDK 7+) 或 finally 塊保證釋放
- 連接池:生產環境必須使用 Druid、HikariCP 等連接池,避免頻繁創建銷毀
// JDK 7+ try-with-resources 自動關閉
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
// 業務邏輯
}
常見問題排查
ClassNotFoundException:驅動 JAR 未加入 classpath
Communications link failure:URL/端口/防火牆/數據庫服務狀態
SQLException: Access denied:用戶名密碼/權限/主機白名單
- 中文亂碼:URL 添加
?characterEncoding=utf8&useSSL=false
進階提示
- 使用
PreparedStatement 防 SQL 注入、預編譯優化
- 批量操作
addBatch() / executeBatch() 提升性能
- 事務控制:
conn.setAutoCommit(false) + commit()/rollback()