Jdbc事务

事务模拟转账

A向B转账100元,基于事务的ACID原则,前后的总钱数必须一致,简单的sql语句如下,而且两个语句一起执行才能完成转账这一事务,否则金额会出错。

update account set money= money-100 where name='A'

update account set money= money+100 where name='B'

代码实现

public class TestTransation {
    private static Connection connection=null;
    private static PreparedStatement statement=null;
    private static ResultSet resultSet=null;

    public static void main(String[] args) throws SQLException {
        try {
            connection= JDBCutil.getConnection(); //JDBCutil为个人编写的数据库连接工具类
            //关闭数据库的自动提交,自动会开启事务
            connection.setAutoCommit(false);

            String sql1="update account set money= money-100 where name='A'";
            statement= connection.prepareStatement(sql1);
            statement.executeUpdate();

            String sql2="update account set money= money+100 where name='B'";
            statement= connection.prepareStatement(sql2);
            statement.executeUpdate();
            connection.commit();
            System.out.println("成功");
        } catch (SQLException throwable) {
            try {
                connection.rollback();   //失败回滚事务
                System.out.println("失败");
            } catch (SQLException throwable1) {
                throwable1.printStackTrace();
            }
        } finally {
            JDBCutil.release(resultSet,statement,connection);
        }

    }
}

执行前:

image-20210205150103117

执行后:

image-20210205150203469

原文地址:https://www.cnblogs.com/xiaxiaopi/p/14377817.html