Loading

JDBC | 第四章: JDBC之Transaction事务提交与回滚

默认情况下,当我们创建一个数据库连接时,会运行在自动提交模式(Auto-commit)下。这意味着,任何时候我们执行一条SQL完成之后,事务都会自动提交。所以我们执行的每一条SQL都是一个事务,并且如果正在运行DML或者DDL语句,这些改变会在每一条SQL语句结束的时存入数据库。有时候我们想让一组SQL语句成为事务的一部分,那样我们就可以在所有语句运行成功的时候提交,并且如果出现任何异常,这些语句作为事务的一部分,我们可以选择将其全部回滚。

让我们通过一个简单的示例理解一下,这里使用JDBC的事务管理来支持数据的完整性

 /*
     * 发生异常回滚所有执行更新的sql
     * */
    public void insrolledAll() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        PreparedStatement preparedStatement1 = null;
        //这里参数用?占位符表示
        String sqlTeacher = "insert into teacher ( name, age, hobby, addr) values (?,?,?,?)";
        String sqlStudent = "insert into student (name, age, addr, hobby) values (?,?,?,?)";
        try {
            //获取数据连接
            connection = basicUse.getConnection();
            //设置事务自动提交为手动提交
            connection.setAutoCommit(false);

            //获取发送sql指令执行sql进行预编译
            preparedStatement = connection.prepareStatement(sqlStudent);

            //设置sql语句参数索引从1开始
            preparedStatement.setObject(1, "Tom");
            preparedStatement.setObject(2, 24);
            preparedStatement.setObject(3, "上海");
            preparedStatement.setObject(4, "篮球");
            preparedStatement.executeUpdate();
            System.out.println("执行sqlStudent" + sqlStudent);

            //手动制造异常
            int i = 10 / 0;

            preparedStatement1 = connection.prepareStatement(sqlTeacher);
            preparedStatement1.setObject(1, "kenx");
            preparedStatement1.setObject(2, 24);
            preparedStatement1.setObject(3, "足球");
            preparedStatement1.setObject(4, "北京");
            preparedStatement1.executeUpdate();
            System.out.println("执行sqlTeacher" + sqlTeacher);

            //提交事务
            connection.commit();

        } catch (Exception e) {
            //回滚事务
            try {
                connection.rollback();
                System.out.println("JDBC Transaction rolled back successfully");
            } catch (SQLException e1) {
                System.out.println("SQLException in rollback" + e1.getMessage());
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            //执行完数据库操作后记得关闭数据库连接资源
            try {
                preparedStatement.close();
                preparedStatement1.close();
                connection.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

JDBC Savepoint示例

有时候一个事务可能是一组复杂的语句,因此可能想要回滚到事务中某个特殊的点。JDBC Savepoint帮我们在事务中创建检查点(checkpoint),这样就可以回滚到指定点。当事务提交或者整个事务回滚后,为事务产生的任何保存点都会自动释放并变为无效。把事务回滚到一个保存点

 /*
     * 发生异常回滚到指定的位置
     * */
    public void insrolledSavepoint() {
        Savepoint savepoint = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        PreparedStatement preparedStatement1 = null;
        //这里参数用?占位符表示
        String sqlTeacher = "insert into teacher ( name, age, hobby, addr) values (?,?,?,?)";
        String sqlStudent = "insert into student (name, age, addr, hobby) values (?,?,?,?)";
        try {
            //获取数据连接
            connection = basicUse.getConnection();
            //设置事务自动提交为手动提交
            connection.setAutoCommit(false);

            //获取发送sql指令执行sql进行预编译
            preparedStatement = connection.prepareStatement(sqlStudent);

            //设置sql语句参数索引从1开始
            preparedStatement.setObject(1, "JDBC");
            preparedStatement.setObject(2, 24);
            preparedStatement.setObject(3, "上海");
            preparedStatement.setObject(4, "篮球");
            preparedStatement.executeUpdate();
            System.out.println("执行sqlStudent" + sqlStudent);


            //设置回滚的点  失败只会回滚老师信息
            savepoint = connection.setSavepoint("teacher");

            preparedStatement1 = connection.prepareStatement(sqlTeacher);
            preparedStatement1.setObject(1, "kenx");
            preparedStatement1.setObject(2, 24);
            preparedStatement1.setObject(3, "足球");
            preparedStatement1.setObject(4, "北京");
            preparedStatement1.executeUpdate();
            System.out.println("执行sqlTeacher" + sqlTeacher);

               //手动制造异常
               int i = 10 / 0;
            //提交事务
            connection.commit();


        } catch (Exception e) {
            //回滚事务
            try {
                if (StrUtil.isEmptyIfStr(savepoint)) {
                    //回滚所有更新sql
                    connection.rollback();
                    System.out
                            .println("JDBC Transaction rolled back successfully");
                } else {
                    connection.rollback(savepoint);
                    System.out.println("JDBC Transaction rolled back successfully");
                    connection.commit();
                }

            } catch (SQLException e1) {
                System.out.println("SQLException in rollback" + e1.getMessage());
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            //执行完数据库操作后记得关闭数据库连接资源
            try {
                preparedStatement.close();
                preparedStatement1.close();
                connection.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

完整项目案例
点击这里 github

posted @ 2020-08-24 12:21  程序员三时  阅读(1335)  评论(1编辑  收藏  举报