国庆节10月1日
--


基于JDBC执行INSERT/UPDATE/DELETE等DML语句,掌握executeUpdate方法的使用。
JDBC中执行增删改(DML)操作通过 PreparedStatement.executeUpdate() 方法完成,返回值为受影响的记录行数。
1// 1. 建立数据库连接2Connection conn = DriverManager.getConnection(3 "jdbc:mysql://localhost:3306/web", "root", "1234");4
5// 2. SQL语句(预编译)6String sql = "UPDATE user SET password = ?, age = ? WHERE id = ?";7
8// 3. 创建PreparedStatement9PreparedStatement pstmt = conn.prepareStatement(sql);10
11// 4. 设置参数12pstmt.setString(1, newPassword);13pstmt.setInt(2, newAge);14pstmt.setInt(3, userId);15
16// 5. 执行更新17int rowsUpdated = pstmt.executeUpdate();18
19// 6. 关闭资源20pstmt.close();21conn.close();| 操作类型 | 方法 | 返回值 |
|---|---|---|
| DML(INSERT/UPDATE/DELETE) | executeUpdate() | int — 影响的记录数 |
| DQL(SELECT) | executeQuery() | ResultSet — 查询结果集 |
JDBC默认自动提交。如需手动控制事务:
1conn.setAutoCommit(false); // 关闭自动提交2// ... 执行多条DML ...3conn.commit(); // 手动提交4// 或 conn.rollback(); // 出错时回滚PreparedStatement),防止SQL注入。PreparedStatement 和 Connection。executeUpdate() 返回值可用于判断操作是否成功(影响行数 > 0)。如果你喜欢,那么欢迎来到我的世界!
了解更多暂未播放



"所有的相遇都是久别重逢。"—— 未知


