Java transaction control of database learning

1. Affairs

A database transaction (transaction) is a sequence of database operations that access and possibly manipulate various data items. These operations are either executed or not executed at all, and are an indivisible unit of work. A transaction consists of all database operations performed between the start of the transaction and the end of the transaction.
For example, when we go to a bank to transfer money, the operation can be divided into the following two steps:
(1) Withdraw money from the first account. String sql1;
(2) Deposit the money into the second account. String sql2;
In this process, the two links are related. **The funds from the first account must be correctly deposited into the second account. If the second link is not completed, the entire process should be cancelled, otherwise the problem of lost funds will occur. **The entire transaction process can be regarded as one thing. Success means all success, and failure means all cancellation. This can avoid data inconsistency when there is a problem in the middle of the operation.

2. Specific Java applications

In a project, the following three statements are required to form a transaction

String sql = "insert into Train_ticket (user_id,train_id,start_station_name,end_station_name,carriage,seat_grade,seat_location,ride_time,start_time,end_time,price) " +
                "values ('"+ticket.getUser_id()+"','"+ticket.getTrain_id()+"','"+ticket.getStart_station_name()+"','"+ticket.getEnd_station_name()+"',"+ticket.getCarriage()+","+ticket.getSeat_grade()+"," +
                "'"+ticket.getSeat_location()+"','"+ticket.getRide_time()+"','"+ticket.getStart_time()+"','"+ticket.getEnd_time()+"',"+ticket.getPrice()+");";

        String sql2 = "update Train_seat set occupy=0 where train_id='"+ticket.getTrain_id()+"' and carriage="+ticket.getCarriage()+" and seat_location='"+ticket.getSeat_location()+"'";
        String sql3 = "insert into Ride_train values ('"+ticket.getUser_id()+"','"+ticket.getTrain_id()+"',' "+ticket.getRide_time()+"   "+ticket.getStart_time()+"')";

How to ensure its atomicity:
use transaction commit and rollback

Encapsulate the SQL statements that make up the transaction into a method, or commit unevenly, or fail unevenly

/***
 * 数据库的事务并发控制
 */
public class Affairs {
    
    

    static Connection conn=null;
    static {
    
    
        conn=DBConnection.getConnection();
    }

    public static int  transaction_control(String sql[]){
    
    

        Statement stmt = null;

        int result = 0;

        try {
    
    

            // 开启事务
            //不把其设置为true之前都是一个当作一个事务来处理
            conn.setAutoCommit(false);

            // 创造SQL语句

            // 执行SQL语句
            stmt = conn.createStatement();
            for (int i = 0; i < sql.length; i++) {
    
    
                stmt.executeUpdate(sql[i]);
            }

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

            System.out.println( "OK!" );
        }
        //发生任何错误均需回滚
        catch (SQLIntegrityConstraintViolationException e3) {
    
    

            result = -1;//主码冲突,返回支付失败
            try {
    
    
                // 回滚事务
                //撤销上面对事务的所有操作哈!
                conn.rollback();
            }  catch (SQLException e2){
    
    

            }

        } catch (Exception e) {
    
    
            e.printStackTrace();
            System.out.println("有错误!");

            try {
    
    
                // 回滚事务
                //撤销上面对事务的所有操作哈!
                conn.rollback();
            }  catch (SQLException e2){
    
    

            }
        }

        return result;

    }

}

Tool DBConnection

//com.mysql.cj.jdbc.Driver数据库驱动
    private static final String DBDRIVER="com.mysql.cj.jdbc.Driver";
    //IP地址202.194.14.120  端口号3306    数据库的名字TrainTicketSystem
    private static final String DBURL="jdbc:mysql://localhost:3306/TrainTicketSystem?&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
    //用户名root
    private static final String DBUSER="root";
    //密码***
    private static final String DBPASSWORD="***";
    static {
    
    
        try {
    
    
            Class.forName(DBDRIVER);
            System.out.println("加载驱动成功");
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
            System.out.println("加载驱动失败");
        }
    }
    public static Connection getConnection() {
    
    
        Connection conn=null;
        try {
    
    
            conn=DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
            System.out.println("连接成功");
        } catch (SQLException e) {
    
    
            // TODO: handle exception
            e.printStackTrace();
            System.out.println("发生连接异常");
        }
        return conn;
    }

3. The key

Before execution, there must be conn.setAutoCommit( false ); this sentence is to set no automatic submission, if automatic submission is equivalent to a SQL statement is a transaction.
If conn.setAutoCommit( true) then it is to set automatic submission, first The sentence can be submitted and the database will have corresponding records, but the second sentence cannot be rolled back if an error is reported.
Summary: Before the transaction is rolled back, conn.setAutoCommit( false ); in this way, the following statement is equivalent to a transaction, once an error occurs, all operations will be undone.

Guess you like

Origin blog.csdn.net/joey_ro/article/details/108761522