JDBC Transaction processing-Four principles
Atomic Nature
Consistency
Isolation of
Durability
The first step: realize the transfer operation
Assuming that in the account, Galen has a balance of 5000 yuan, Nerf has a balance of 2000 yuan,
Galen wants to transfer 1000 yuan to nerf.
public static void Outmoney (Connection conn,string name,int account) throws sqlexception{string sql= "Update t_account set Balance=balance-? where name=? "; PreparedStatement pst=conn.preparestatement (SQL);p St.setint (1, account);p st.setstring (2, name); int result= Pst.executeupdate ();p st.close ();} public static void Inmoney (Connection conn,string name,int account) throws sqlexception{string sql= "Update T_account set B Alance=balance+? where name=? "; PreparedStatement pst=conn.preparestatement (SQL);p St.setint (1, account);p st.setstring (2, name); int result= Pst.executeupdate ();p st.close ();}
System.out.println ("Galen is transferring $1000 to Nerf");//Transfer operation try {Outmoney (conn, "Galen", +), Inmoney (conn, "Nerf", +);} catch ( SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally{try {System.out.println ("Transfer successful! "); Conn.close ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}
Run:
The normal transfer was successful.
Assume that the public static void Inmoney (Connection conn,string name,int account) is running unexpectedly.
Artificial construction accident
Then run the program
View data for a database
Galen 1000 yuan Less, Nerf balance has not changed!
In this way, Nerf on the pit!!!
Improved
The required functions
Con.setautocommit (FALSE); Cancel Auto-Commit
Con.rollback (); Rolling back
Con.commit (); Commit a transaction
Transaction processing-rollback (transfer operation)