The JDBC API provides the Setautocommit () method through which we can disable autocommit database connections. Autocommit should be disabled because only such transactions are not automatically committed unless the connection's commit () method is called. The database server uses table locks to implement transaction management, and it is a strained resource. Therefore, the transaction should be committed as soon as possible after the operation is completed. Let's write another program, where I'll use the JDBC Transaction Management feature to ensure that the integrity of the data is not compromised.
..........
Try{con=dbconnection.getconnection (); //set auto commit to FalseCon.setautocommit (false); //dobusiness
//Now COMMIT TRANSACTIONCon.commit (); } Catch(SQLException e) {e.printstacktrace (); Try{con.rollback (); System.out.println ("JDBC Transaction rolled back successfully"); } Catch(SQLException E1) {System.out.println ("SQLException in Rollback" +e.getmessage ()); } }
.............
Sometimes a transaction can be a complex set of statements, so you might want to roll back to a particular point in the transaction. The JDBC savepoint helps us create checkpoints (checkpoint) in the transaction so that we can roll back to the specified point. When a transaction commits or the entire transaction is rolled back, any savepoint generated for the transaction is automatically freed and becomes invalid. Rolling a transaction back to a savepoint causes all other savepoint to be automatically freed and becomes invalid.
SavePoint savepoint =NULL; Try{con=dbconnection.getconnection (); //set auto commit to FalseCon.setautocommit (false); do business
//if code reached here, means main work was done successfullySavePoint = Con.setsavepoint ("SavePoint1"); Insertlogdata (Con,2); //Now COMMIT TRANSACTIONCon.commit (); } Catch(SQLException e) {e.printstacktrace (); Try { if(SavePoint = =NULL) { //SQLException occurred in saving to Employee or Address//TablesCon.rollback (); System.out.println ("JDBC Transaction rolled back successfully"); } Else { //exception occurred in inserting to Logs table//we can ignore it by rollback to the savepointCon.rollback (savepoint); //lets commit nowCon.commit (); } } Catch(SQLException E1) {System.out.println ("SQLException in Rollback" +e.getmessage ()); } }
The content is from http://www.importnew.com/8832.html.
JDBC Transaction management and SavePoint example