JDBC 是 Java 操作關係數據庫的基石,雖然生產多用 MyBatis/Hibernate,但理解 JDBC 原理對排查 ORM 問題、優化 SQL、閱讀框架源碼至關重要。
mysql:mysql-connector-java)CREATE DATABASE imooc;
USE imooc;
CREATE TABLE goddess (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
mobile VARCHAR(20),
email VARCHAR(100),
address VARCHAR(200)
);
INSERT INTO goddess (name, mobile, email, address) VALUES
('林志玲', '13800001111', 'lin@example.com', '台北市信義區'),
('劉亦菲', '13900002222', 'liu@example.com', '北京市朝陽區');
src/main/java ├── com.czgo.db # 數據庫工具 ├── com.czgo.model # 實體類 ├── com.czgo.dao # 數據訪問層 └── com.czgo.action # 業務/控制層
public class Goddess implements Serializable {
private Integer id;
private String name, mobile, email, address;
// Getter/Setter 省略
}
public class DBUtil {
private static final String URL = "jdbc:mysql://127.0.0.1:3306/imooc?useSSL=false&characterEncoding=UTF-8";
private static final String USER = "root";
private static final String PASS = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASS);
}
public static void close(Connection c, Statement s, ResultSet r) {
try { if (r != null) r.close(); } catch (SQLException e) {}
try { if (s != null) s.close(); } catch (SQLException e) {}
try { if (c != null) c.close(); } catch (SQLException e) {}
}
}
public class GoddessDao {
// 查詢全部
public List query() throws SQLException {
String sql = "SELECT id,name,mobile,email,address FROM goddess";
try (Connection c = DBUtil.getConnection();
PreparedStatement ps = c.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
List list = new ArrayList<>();
while (rs.next()) {
Goddess g = new Goddess();
g.setId(rs.getInt("id"));
g.setName(rs.getString("name"));
g.setMobile(rs.getString("mobile"));
g.setEmail(rs.getString("email"));
g.setAddress(rs.getString("address"));
list.add(g);
}
return list;
}
}
// 按 ID 查詢
public Goddess queryById(Integer id) throws SQLException { ... }
// 新增
public void add(Goddess g) throws SQLException {
String sql = "INSERT INTO goddess(name,mobile,email,address) VALUES(?,?,?,?)";
try (Connection c = DBUtil.getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, g.getName());
ps.setString(2, g.getMobile());
ps.setString(3, g.getEmail());
ps.setString(4, g.getAddress());
ps.executeUpdate();
}
}
// 修改
public void update(Goddess g) throws SQLException { ... }
// 刪除
public void delete(Integer id) throws SQLException { ... }
}
public class GoddessAction {
private GoddessDao dao = new GoddessDao();
public void add(Goddess g) throws Exception { dao.add(g); }
public Goddess get(Integer id) throws SQLException { return dao.queryById(id); }
public void edit(Goddess g) throws Exception { dao.update(g); }
public void del(Integer id) throws SQLException { dao.delete(id); }
public List query() throws Exception { return dao.query(); }
// 測試入口
public static void main(String[] args) throws Exception {
GoddessAction action = new GoddessAction();
action.query().forEach(g ->
System.out.println(g.getName() + " | " + g.getMobile() + " | " + g.getEmail()));
}
}
林志玲 | 13800001111 | lin@example.com 劉亦菲 | 13900002222 | liu@example.com
Connection.setAutoCommit(false) + try-catch-finally commit/rollbackGoddessDao 介面,便於測試與多實現切換RowMapper 介面,減少樣板代碼LIMIT offset, size + 總數查詢PreparedStatement,拒絕字符串拼接 SQLcom.mysql.cj.jdbc.DriveruseSSL=false、serverTimezone=Asia/Shanghai、characterEncoding=UTF-8try-with-resources 自動關閉,避免洩漏本文通過完整的 MVC 分層實現 JDBC CRUD,展示了從數據庫建表、實體映射、DAO 封裝到業務調用的標準流程。掌握 JDBC 核心 API(Connection、PreparedStatement、ResultSet)與資源管理模式,是進階學習 MyBatis、Spring Data JPA 等 ORM 框架的紮實基礎。