Transaction processing process 1. blocking automatic commit function 2. Transaction Processing 3. Restoring the automatic commit function the data table before the code instance executes the program looks like prenamecodeclassjavaimportjavasjavasql *; publicclassGetConnection {publicsta transaction processing process
1. disable the automatic submission function
2. process transactions
3. restore the automatic submission function
Code instance
Data table before executing the program
public class GetConnection{public static void main(String[] args){Access2Database adb=new Access2Database();Connection conn=adb.getConn();//transaction dealingPreparedStatement pstam=null;try{conn.setAutoCommit(false);String sql="delete from student where name='a' and major=?";pstam=conn.prepareStatement(sql);pstam.setString(1, "Chinese");pstam.executeUpdate();conn.rollback();conn.commit();}catch(SQLException e){try {conn.rollback();} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}e.printStackTrace();}finally{try {conn.setAutoCommit(true);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//release the resource of the programtry{pstam.close();conn.close();}catch(SQLException e){e.printStackTrace();}}}
Later
As you can see, the transaction is rolled back successfully.
========================================================== ====================================
In addition, the application can also save the intermediate state of transaction processing and restore to this intermediate state of storage.
Status before data table
View code
import java.sql.*;public class GetConnection{public static void main(String[] args){Access2Database adb=new Access2Database();Connection conn=adb.getConn();//transaction dealingPreparedStatement pstam=null;try{conn.setAutoCommit(false);String sql="delete from student where name='a' and major=?";pstam=conn.prepareStatement(sql);pstam.setString(1, "Chinese");pstam.executeUpdate();//conn.commit();Savepoint sp=conn.setSavepoint();sql="insert into student(name,major,score) values('g','Math','99');";pstam=conn.prepareStatement(sql);pstam.executeUpdate();conn.rollback(sp);conn.commit();}catch(SQLException e){try {conn.rollback();} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}e.printStackTrace();}finally{try {conn.setAutoCommit(true);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//release the resource of the programtry{pstam.close();conn.close();}catch(SQLException e){e.printStackTrace();}}}