事务&数据库连接池&DBUtils

1. 事务

1. Transaction:一组操作中,包含有很多单一的逻辑。只要有一个逻辑没有执行成功,都算失败。所有的数据都回归到最初的状态。

2. 为什么要有事务:为了确保逻辑的成功,例如:银行的转账

3. 使用命令行方式

可以使用set autocommit = off;来关闭自动提交

update account set money = money - 100 where id = 1;

此时虽然命令行中查询的结果会发生改变,但是可以使用

commit:提交事务,数据将会写到磁盘上面的数据库

rollback:数据回滚,回到最初的状态

选择是否提交

4. 使用代码的方式

事务是针对连接的

public void testTransaction(){
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try{
        con = JDBCUtil.getCon();
        // 默认的连接事务是自动提交的,关闭自动提交
        con.setAutoCommit(false);
        String sql = "update account set money = money - ? where id = ?";
        ps = con.prepareStatement(sql);
        ps.setInt(1, 100);
        ps.setInt(2, 1);
        ps.executeUpdate();
        
        ps.setInt(1, -100);
        ps.setInt(2, 1);
        ps.executeUpdate();
        
        con.commit();
        
        /*while(rs.next()){
            String name = rs.getString("name");
            int money = rs.getInt("money");
            System.out.println("name:" + name + ",money:" + money);
        }*/
    } catch(Exception e){
        try {
            con.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    } finally{
        JDBCUtil.release(con, ps, rs);
    }
}

猜你喜欢

转载自www.cnblogs.com/feng-ying/p/9852706.html