Java JDBC程序中对于数据库事务的处理详解

一、JDBC中对于事务的介绍
在这里插入图片描述
二、使用事务模拟经典的转账业务
在这里插入图片描述
下面代码中演示JDBC中没有使用事务,和使用事务的两种情况

//演示jdbc 中如何使用事务
public class Transaction_ {
    
    

    //没有使用事务
    @Test
    public void noTransaction() {
    
    
        //1.得到连接
        Connection connection = null;

        //2.组织一个sql
        //更新记录
        String sql = "UPDATE ACCOUNT SET balance=balance-100 WHERE id=1";
        String sql2 = "UPDATE ACCOUNT SET balance=balance+100 WHERE id=2";

        PreparedStatement preparedStatement = null;
        //创建PrepareStatement对象
        try {
    
    
            connection = JDBCUtils.getConnection(); //在默认情况下,connection对象是默认自动提交的
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();

            int i = 1 / 0;
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            //关闭资源
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }

	//使用事务
    @Test
    public void useTransaction() {
    
    
        //1.得到连接
        Connection connection = null;

        //2.组织一个sql
        //更新记录
        String sql = "UPDATE ACCOUNT SET balance=balance-100 WHERE id=1";
        String sql2 = "UPDATE ACCOUNT SET balance=balance+100 WHERE id=2";

        PreparedStatement preparedStatement = null;
        //创建PrepareStatement对象
        try {
    
    
            connection = JDBCUtils.getConnection(); //在默认情况下,connection对象是默认自动提交的
            //将connection 设置为不自动提交
            connection.setAutoCommit(false);//开启事务
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();

//            int i = 1 / 0;
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();

            //这里提交事务
            connection.commit();
        } catch (SQLException e) {
    
    
            //这里我们可以进行回滚,即撤销执行的sql
            //默认回滚到事务开始的状态
            try {
    
    
                connection.rollback();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
            e.printStackTrace();
        } finally {
    
    
            //关闭资源
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }
}

说明:这里使用到了JDBCUtils这个工具类 在这篇文章

Java 中封装JDBC连接到JDBCUtils工具类的详解

猜你喜欢

转载自blog.csdn.net/lu202032/article/details/124587868