JDBC for transaction management

 

JDBC for transaction management

Four characteristics of a transaction:
Atomicity: It means that the operations contained in the transaction are regarded as a logical unit
Consistency: The database is in a consistent state before and after the end
Isolation: Multiple transactions that modify the database are mutually exclusive The impact on the system after an isolated
persistent transaction completes is permanent

 

Here is an example: there are two tables, one is the user table, the other is the address table, and the user table and the address table are related by user_id. Now I want to insert a person's information, I need to insert data into two tables, as follows:

insert into tbl_user(id,name,password,email)
                   values(10,'xiongda','123','[email protected]')
insert into tbl_address(id,city,country,user_id)
                   values(1,'hangzhou','china',10)

When there is a problem now, the id of the second statement is duplicated with other data in the table, and there is a primary key conflict. If transaction management is not added, it can only cause data to be inserted into the user table, but the address table cannot insert data.

We regard the insert operation of these two tables as a transaction, which also destroys the consistency of the transaction.

So we have to do, either insert all or none of them, that is, to satisfy the atomicity of the transaction.

The code for implementing transaction management in JDBC is as follows:

public class TransactionTest {
    public static Connection getConnection(){
        Connection conn=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            conn=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=FALSE&serverTimezone=UTC","root","xb199795");
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    public static void insertUser(Connection conn) throws SQLException {
        String sql="insert into tbl_user(id,name,password,email)"+
                   "values(10,'xiongda','123','[email protected]')";
            Statement st=conn.createStatement();
            int count=st.executeUpdate(sql);
            System.out.println( "Insert "+count+" records into the user table!" );
    }
    public static void insertAddress(Connection conn) throws SQLException {
        String sql="insert into tbl_address(id,city,country,user_id)"+
                   "values(1,'hangzhou','china',10)";
            Statement st=conn.createStatement();
            int count=st.executeUpdate(sql);
            System.out.println( "Insert "+count+" records into the address table!" );
    }
    public static void main(String[] args) {
        Connection conn =getConnection();
        try {
            conn.setAutoCommit(false);
            insertUser(conn);
            insertAddress(conn);
            conn.commit();
        } catch (SQLException e) {
            System.out.println( "************Exception in transaction processing ***********" );
            e.printStackTrace ();
            try {
                conn.rollback();
                System.out.println( "************Transaction rolled back successfully ***********" );
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }finally {
                try {
                    conn.close();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    }
}

There is no new data in the user table.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325620442&siteId=291194637