JDBC-事务transaction

本文对比了Java中不开启事务与开启事务的情况,讨论了自动提交的默认行为和如何通过设置Savepoint进行事务控制,确保数据一致性。
摘要由CSDN通过智能技术生成

不开启事务

  • 当程序异常时,可能两条语句一条成果一条失败,导致数据库错误的被操作
  • 如下代码,sql1被成功执行,但sql2由于异常未被执行
  • 因为connection默认情况下是自动提交
	private Connection connection = null;

    @Test
    public void notTransaction() {
        String sql1 = "update account set money = money + 100 where id = 1";
        String sql2 = "update account set money = money - 100 where id = 2";
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection(); // 默认情况下connection是自动提交
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

            int i = 1 / 0;// 抛出异常

            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(null, preparedStatement, connection);
        }

开启事务

  • 事务可以确保语句要么都被执行,要么都不执行(回滚),或者选择执行哪一部分(回滚一部分)
  • 这样子可以确保sql1和sql2都被执行或者都不执行
	@Test
    public void useTransaction(){
        String sql1 = "update account set money = money + 100 where id = 1";
        String sql2 = "update account set money = money - 100 where id = 2";
        PreparedStatement preparedStatement = null;
        Savepoint savepoint = null;
        try {
            connection = JDBCUtils.getConnection(); // 默认情况下connection是自动提交
            // 将自动提交取消
            connection.setAutoCommit(false); //相当于开启了事务
            //savepoint = connection.setSavepoint(); // 可以设置回滚点
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

            int i = 1 / 0;// 抛出异常

            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();

            //提交事务
            connection.commit(); // 手动提交
        } catch (SQLException e) {
            try {
                //未设置回滚点,默认回滚到事务开始的地方
                //connection.rollback(savepoint);
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值