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。

  • 相关阅读:
    python基础练习:
    py+selenium切换到新弹出窗口通用方法
    Python 异常处理
    验证码自动化认证部分,可能由于分辨率导致截图不正确
    基于Tesseract的OCR图像识别
    Spark相关知识
    Hive和数据库除了拥有类似的查询语言,再无类似之处;关系型数据库和非关系型数据库的优缺点
    sed替换^A(01),02,03等特殊字符
    Python操作adb命令脚本
    python从放弃到放弃
  • 原文地址:https://www.cnblogs.com/kuracola/p/7440694.html
Copyright © 2011-2022 走看看