2018-02-25 使用jdbc实现事务回滚(二)

笔记如下

Start transaction ----开启事务
...
Rollback ---- 回滚事务
Commit---- 提交事务

/*
     * 设置回滚点是为了提高效率
     * 
     */
    
    //回滚点的使用
    @Test
    public void test2() {
        
        Connection conn =null;
        Statement stmt=null;
        Savepoint sp = null;
        
        try {
            
            conn = JdbcUtils.getConnection();
            
            conn.setAutoCommit(false);
            
            stmt = conn.createStatement();
            
            
            //设置回滚点,在小单元的前面
            sp = conn.setSavepoint();
            
            
            //aaa----bbb转账一百
            stmt.executeUpdate("update account set money=money-100 where name='aaa'");
            stmt.executeUpdate("update account set money=money+100 where name='bbb'");
            
            
            
            //设置回滚点,在小单元的后面
            sp = conn.setSavepoint();
            
            
            //bbb ----ccc转账一百
            stmt.executeUpdate("update account set money=money-100 where name='bbb'");
            stmt.executeUpdate("update account set money=money+100 where name='ccc'");
        
        } catch (Exception e) {
            // TODO: handle exception
            
            try {
                conn.rollback(sp);
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            
            try {
                conn.commit();//确认了开启事务到回滚点这段的操作
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            JdbcUtils.release(null, stmt, conn);
            
        }
        
        
        
    }

你可能感兴趣的:(2018-02-25 使用jdbc实现事务回滚(二))