Transaction one.
What is a transaction?
is to execute a set of SQL instructions, which either executes successfully or all fails if one fails
Two. Operation of the transaction
Note: The connection method is related to transactional operations
The same transaction requires the same connection implementation class object
Process:
To open a transaction:
Con.setautocommit (false);//Turn off autocommit
True to turn on auto-commit
Commit a transaction
Con.commit ();
Rolling back a transaction
Con.rollback ();
Analysis of small transfer cases:
2 Try3{//Turn on transaction: The system will then treat all of the following SQL execution as a whole4 inti = update:-1005 intj = update:+1006 if(i > 0 && J > 0){7 //COMMIT TRANSACTION: When all SQL instructions are executed successfully, all operations on the database, commit transactions, will be permanent and cannot be changed8System.out.println ("Successful transfer!"));9 }Ten}Catch(Exception e) One { A //Rollback Transaction: When there is a problem in your transaction and not all execution succeeds, review the transaction so that all previous operations on the database are revoked -}
Code Demo:
1 Public classDemo {2 Public Static voidMain (string[] args) {3Connection con=NULL;4 Try{5Queryrunner QR =NewQueryrunner ();6con=c3p0utils.getconnection ();7 //Open Transaction8Con.setautocommit (false);9 intRe1 = qr.update ("Update account set money=money-?") Where id=? ", 300,342);Ten intRe2 = qr.update ("Update account set money=money+?") Where id=? ", 300,345); One if(re1>0&&re2>0){ A //both execute a successful commit transaction - con.commit (); -}Else{ the //failure to perform a manual rollback of a transaction - Con.rollback (); - } -}Catch(Exception e) { + //exception rollback TRANSACTION occurred - Try { + Con.rollback (); A}Catch(SQLException E1) { at //TODO auto-generated Catch block - e1.printstacktrace (); - } -}finally { - Try { - //put the connection back into the connection pool in con.close (); -}Catch(SQLException e) { to //TODO auto-generated Catch block + e.printstacktrace (); - } the } * } $}
The Java Learning Notes business