当前位置:网站首页>JDBC | Chapter 4: transaction commit and rollback

JDBC | Chapter 4: transaction commit and rollback

2022-07-02 20:24:00 Mr. dujiu QAQ

Transaction-JDBC management

JDBC The default is automatic transactions :
perform sql sentence :executeUpdate() ---- Every time executeUpdate Method representative Transaction auto commit
So you have to go through jdbc Of API Manual transactions :
Open transaction :conn.setAutoCommit(false);
Commit transaction :conn.commit();
Roll back the transaction :conn.rollback();
Be careful : Controlling transactions connnection Must be the same
perform sql Of connection With opening transactions connnection It must be the same to control the transaction .

Transaction Example :

import java.sql.*;

public class Jdbc {

    public static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";


    public static void main(String[] args) throws Exception {
        //1. Load driver 
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.  Get database connection 
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        //3. Operating the database , We will increase, delete, and change inspections 
        String sql = "insert into class (id, teacher_id) values (?,?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        try {
            // Set transaction auto commit to manual commit 
            conn.setAutoCommit(false);
            for (int i = 20; i < 30; i++) {
                preparedStatement.setObject(1, i);
                preparedStatement.setObject(2, i);
                preparedStatement.addBatch();
            }
            int [] success = preparedStatement.executeBatch();
            System.out.println(success.length);
            // Manual manufacturing abnormality 
            int m = 10 / 0;
            for (int i = 30; i < 40; i++) {
                preparedStatement.setObject(1, i);
                preparedStatement.setObject(2, i);
                preparedStatement.addBatch();
            }
            int [] success2 = preparedStatement.executeBatch();
            System.out.println(success2.length);
            // Commit transaction 
            conn.commit();

        }  catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
                System.out.println("JDBC Transaction rolled back successfully");
            } catch (SQLException e1) {
                System.out.println("SQLException in rollback" + e1.getMessage());
                e1.printStackTrace();
            }

        } finally {
            // Remember to close the database connection resource after executing the database operation 
            try {
                preparedStatement.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }
}

Abnormal information :

JDBC Savepoint

Sometimes a transaction may be a complex set of statements , Therefore, you may want to rollback to a special point in the transaction .JDBC Savepoint Help us create checkpoints in transactions (checkpoint), In this way, you can rollback to the specified point . After the transaction is committed or the whole transaction is rolled back , Any savepoints generated for a transaction are automatically released and become invalid . Rollback the transaction to a savepoint , All other savepoints will be automatically released and become invalid .

step :

1. Create checkpoints in transactions

2. Catch checkpoints in exceptions and roll back to checkpoints

Savepoint Example :

import cn.hutool.core.util.StrUtil;
import java.sql.*;

public class Jdbc {

    public static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";


    public static void main(String[] args) throws Exception {
        //1. Load driver 
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.  Get database connection 
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        //3. Operating the database , We will increase, delete, and change inspections 
        String classSql = "insert into class (id, teacher_id) values (?,?)";
        String userSql = "insert into users (name, age) values (?,?)";
        Savepoint savepoint = null;

        try {
            // Set transaction auto commit to manual commit 
            conn.setAutoCommit(false);
            PreparedStatement preparedStatement1 = conn.prepareStatement(classSql);
            for (int i = 20; i < 30; i++) {
                preparedStatement1.setObject(1, i);
                preparedStatement1.setObject(2, i);
                preparedStatement1.addBatch();
            }
            int [] success = preparedStatement1.executeBatch();
            System.out.println(success.length);
            // Set rollback point    Failure will only roll back users Information 
            savepoint = conn.setSavepoint(" checkpoint ");
            // Manual manufacturing abnormality 
            int m = 10 / 0;
            PreparedStatement preparedStatement2 = conn.prepareStatement(userSql);
            preparedStatement2.setObject(1, " Wrist hero ");
            preparedStatement2.setObject(2, "24");
            preparedStatement2.executeUpdate();
            // Commit transaction 
            conn.commit();

        }  catch (Exception e) {
            e.printStackTrace();
            if (StrUtil.isEmptyIfStr(savepoint)) {
                // Rollback all updates sql
                conn.rollback();
                System.out.println("JDBC Transaction rolled back successfully");
            } else {
                // Rollback to the specified location 
                conn.rollback(savepoint);
                System.out.println("JDBC Transaction rolled back successfully");
                conn.commit();
            }

        } finally {
            // Remember to close the database connection resource after executing the database operation 
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }
}

原网站

版权声明
本文为[Mr. dujiu QAQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202151353228573.html