事务

在使用java执行sql语句的时候, 每次在连接关闭的时候都会执行事务的提交, 因此对于同一个事务中的多个操作, 需要将其放到同一个连接当中

    void transactionTestv2() throws Exception {
        Connection connection = JDBCUtils.getConnection();
//        取消自动提交
        connection.setAutoCommit(false);
        String sql = "update user_table set balance = balance - 100 where user = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setObject(1, "AA");
        preparedStatement.execute();
        preparedStatement.close();

        String sql1 = "update user_table set balance = balance + 100 where user = ?";
        PreparedStatement preparedStatement1 = connection.prepareStatement(sql1);
        preparedStatement1.setObject(1, "BB");
        preparedStatement1.execute();
        preparedStatement1.close();

        connection.commit();
        connection.setAutoCommit(true);
        connection.close();
    }

脏读: 读取未提交的数据, 不可接受

不可重复读: 两次读取数据的值不同, 因为其它事务对其值进行了更新操作, 可接受状态, Oracle默认(读已提交数据)

幻读: 两次读取的数据返回结果不一致, 因为其它事务进行了插入或删除操作, 可接受状态, MySQL默认(可重复读数据)

实现事务的方法

  1. 在一个连接里面执行事务
  2. 关闭自动提交

   转载规则


《》 熊水斌 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
前端基础HTMLinput输入框 type属性: 文本框, 单选框, 复选框, 下拉列表, 提交按钮, 重置按钮 get请求和post请求 get请求会将数据添加到url中, 明文数据不安全 post请求一般用于表单数据提交 当属性名和
2022-11-11
下一篇 
泛型 泛型类 泛型接口 泛型方法 /** * Order是泛型类 */ class Order<T>{ } /** * 此时SubOrder01不是泛型类, 因为指明了Integer */ class SubOrder0
2022-11-11
  目录