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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM