JDBC API提供了setAutoCommit()方法,通过它我们可以禁用自动提交数据库连接。自动提交应该被禁用,因为只有这样事务才不会自动提交,除非调用了连接的commit()方法。数据库服务器使用表锁来实现事务管理,并且它是一种紧张的资源。因此,在操作完成后应该尽快提交事务。让我们编写另外一个程序,这里我将使用JDBC事务管理特性来保证数据的完整性不被破坏。
.......... try { con = DBConnection.getConnection(); // set auto commit to false con.setAutoCommit(false); //doBusiness // now commit transaction con.commit(); } catch (SQLException e) { e.printStackTrace(); try { con.rollback(); System.out.println("JDBC Transaction rolled back successfully"); } catch (SQLException e1) { System.out.println("SQLException in rollback" + e.getMessage()); } } .............
有时候一个事务可能是一组复杂的语句,因此可能想要回滚到事务中某个特殊的点。JDBC Savepoint帮我们在事务中创建检查点(checkpoint),这样就可以回滚到指定点。当事务提交或者整个事务回滚后,为事务产生的任何保存点都会自动释放并变为无效。把事务回滚到一个保存点,会使其他所有保存点自动释放并变为无效。
Savepoint savepoint = null; try { con = DBConnection.getConnection(); // set auto commit to false con.setAutoCommit(false); // do Business // if code reached here, means main work is done successfully savepoint = con.setSavepoint("SavePoint1"); insertLogData(con, 2); // now commit transaction con.commit(); } catch (SQLException e) { e.printStackTrace(); try { if (savepoint == null) { // SQLException occurred in saving into Employee or Address // tables con.rollback(); System.out.println("JDBC Transaction rolled back successfully"); } else { // exception occurred in inserting into Logs table // we can ignore it by rollback to the savepoint con.rollback(savepoint); // lets commit now con.commit(); } } catch (SQLException e1) { System.out.println("SQLException in rollback" + e.getMessage()); } }
内容来自http://www.importnew.com/8832.html。
时间: 2024-11-17 23:29:28