JSP 直接操作數據庫雖不符合分層架構,但理解 JDBC 核心流程是掌握後端開發的基石。本文梳理 SQL 基礎、JDBC 四大核心接口、兩種驅動連接模式與資源管理要點。
| 類別 | 語句 | 範例 |
|---|---|---|
| DDL | CREATE TABLE | CREATE TABLE user(id INT PRIMARY KEY, name VARCHAR(20)); |
| DML | SELECT | SELECT id,name FROM user WHERE age > 18; |
| DML | INSERT | INSERT INTO user(id,name) VALUES(1,'Tom'); |
| DML | UPDATE | UPDATE user SET age=20 WHERE id=1; |
| DML | DELETE | DELETE FROM user WHERE id=1; |
Connection。commit/rollback)、創建 Statement/PreparedStatement。executeQuery 返回 ResultSet,executeUpdate 返回影響行數。next() 逐行讀取,getXxx(column) 取值。Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:myDSN", "user", "pwd");
// MySQL 範例
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC",
"root", "password");
WEB-INF/lib 或容器共享 lib。jdbc:subprotocol://host:port/db?params。String sql = "INSERT INTO user(name,email) VALUES(?,?)";
try (Connection con = getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, "Alice");
ps.setString(2, "alice@example.com");
int rows = ps.executeUpdate();
System.out.println("插入行數:" + rows);
}
Connection/Statement/ResultSet,防洩漏。con.setAutoCommit(false),統一提交/回滾。JSP 中直寫 JDBC 已過時,建議採用 Spring JDBC Template / MyBatis / JPA 封裝數據訪問層,JSP/Controller 僅調用 Service,實現關注點分離。