zoukankan      html  css  js  c++  java
  • JDBC事务管理及SavePoint示例

     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。

  • 相关阅读:
    bzoj 4451 : [Cerc2015]Frightful Formula FFT
    bzoj 3928: [Cerc2014] Outer space invaders
    HDU 5306 线段树
    bzoj 1914: [Usaco2010 OPen]Triangle Counting 数三角形
    bzoj 4519: [Cqoi2016]不同的最小割 最小割树
    bzoj : 4504: K个串 区间修改主席树
    bzoj 4332:JSOI2012 分零食
    bzoj 2595 : [Wc2008]游览计划
    poj 3683 Priest John's Busiest Day
    bzoj 1823: [JSOI2010]满汉全席 && bzoj 2199 : [Usaco2011 Jan]奶牛议会 2-sat
  • 原文地址:https://www.cnblogs.com/kuracola/p/7440694.html
Copyright © 2011-2022 走看看