mysql的“事务“简述

1,事务是什么?

事务是一组SQL语句,要么全部执行成功,要么全部执行失败。通常一个事务对应一个完整的业务 (例如银行账户转账业务,该业务就是一个最小的工作单元)

事务的提交:COMMIT
事务的回滚:ROLLBACK
事务的关闭:CLOSE

2,事务流程

such as 比如:

这是两张表 user和user1

现在我们需要让旺旺给汪汪转十块钱。

public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/ww";
            connection = DriverManager.getConnection(url,"root","132990");
 
//            // 禁止jdbc自动提交事务
//            connection.setAutoCommit(false);
 
            preparedStatement = connection.prepareStatement("update user set money = money-? where id= ?");
            preparedStatement.setInt(1,10);
            preparedStatement.setInt(2,1);
            preparedStatement.executeUpdate();
 
 
            String str = null;
            if(str.equals("")){
 
            }
 
            preparedStatement = connection.prepareStatement("update user1 set money = money+? where id = ?");
            preparedStatement.setInt(1,10);
            preparedStatement.setInt(2,1);
            preparedStatement.executeUpdate();
 

// // 提交事务

//      connection.commit();
    } catch (Exception e) {
        e.printStackTrace();

// // 回滚事务
//

        try {
//                connection.rollback();
//            } catch (SQLException e1) {
//                e1.printStackTrace();
//            }

//关闭资源

}finally {
        try {
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

我们可以观察出两个SQL语句中间会报空指针异常,这个时候我们来 看一下运行结果。

我们可以看到旺旺少了十块钱,但是汪汪没有多十块钱,这显然是不应该被允许的。这个转账过程是一个事务,这两个SQL语句要么全部执行失败,要不全部成功。

所以这个时候我们应该禁止jdbc自动提交事务

connection.setAutoCommit(false); 然后再两条SQl语句执行完之后提交事务

connection.commit(); 如果有异常则回滚事务

  catch (Exception e) {
        e.printStackTrace();
        // 回滚事务
        try {
            connection.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

    }

猜你喜欢

转载自blog.csdn.net/m0_48930261/article/details/107945835