zoukankan      html  css  js  c++  java
  • JDBC 06: 事务(以转账操作为例)

    1.  转账操作 (不添加事务)

    public static void transfer(String username1,String username2,int amount) {
    
            Connection con = null;
            PreparedStatement stmt1 = null;
            PreparedStatement stmt2 = null;
            
            try {
                con = JDBCUtils.getConnection();
                
                String sql = "update user set balance = balance - ? where username = ?";
                stmt1 = con.prepareStatement(sql);
                stmt1.setInt(1, amount);
                stmt1.setString(2,username1);    
                stmt1.executeUpdate();
        
                // 如果在这里出现异常, 则转账人会损失金钱   
                
                sql = "update user set balance = balance + ? where username = ?";
                stmt2 = con.prepareStatement(sql);
                stmt2.setInt(1, amount);
                stmt2.setString(2,username2);
                stmt2.executeUpdate();
                
        
                
            } catch (Exception e) {        
                e.printStackTrace();
            } finally {
                JDBCUtils.close(stmt2, stmt1, con);
            }
        }                          

    2.  转账操作 (添加事务)

    public static void transfer(String username1,String username2,int amount) {
    
            Connection con = null;
            PreparedStatement stmt1 = null;
            PreparedStatement stmt2 = null;
            
            try {
                con = JDBCUtils.getConnection();
                
                con.setAutoCommit(false); // 开启事务
                
                String sql = "update user set balance = balance -? where username =?";
                stmt1 = con.prepareStatement(sql);
                stmt1.setInt(1, amount);
                stmt1.setString(2,username1);    
                stmt1.executeUpdate();
                
            // 在"事务"中, 如果有代码执行不成功,"事务"就不会执行 

    sql
    = "update user set balance = balance + ? where username =?"; stmt2 = con.prepareStatement(sql); stmt2.setInt(1, amount); stmt2.setString(2,username2); stmt2.executeUpdate(); con.commit(); // 提交事务 } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.close(stmt2, stmt1, con); } }
  • 相关阅读:
    编写有效用例_阅读笔记05
    编写有效用例_阅读笔记04
    编写有效用例_阅读笔记03
    编写有效用例_阅读笔记02
    软件需求与分析课堂讨论一
    编写有效用例_阅读笔记01
    问题账户需求分析
    【知识总结】动态 DP
    【知识总结】数论全家桶
    【知识总结】多项式全家桶(三点五)(拆系数解决任意模数多项式卷积)
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13544152.html
Copyright © 2011-2022 走看看