多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
实现事务:调用Connection对象的`setAutoCommit`来关闭和开启自动提交,调用`commit`来提交事务,调用`rollback`回滚事务。 ```java public class StudentTest { /** * 事务 */ @Test public void affair() throws SQLException { Connection conn = null; PreparedStatement pstmt = null; try { //1. 连接数据库 conn = ConnUtils.getConnection3(); //2. 关闭自动提交 conn.setAutoCommit(false); //3. 执行SQL语句 pstmt = conn.prepareStatement("delete from student where id=?"); pstmt.setString(1, "1003"); int result = pstmt.executeUpdate(); //4. 提交事务 conn.commit(); } catch (Exception e) { e.printStackTrace(); try { //5. 如果发生异常则回滚 conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } finally { try { //6. 恢复自动提交 conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } //7. 关闭资源 pstmt.close(); conn.close(); } } } ```