JDBC TRANSACTION:

A database transaction is not completed until the J2EE calls the commit() method. Once commit() method is called none of the SQL statements can be rolled back. By default auto commit is true.
If a j2ee component is processing Transaction then the auto commit feature must be deactivated by calling setAutoCommit() method and passing false parameter. Once the transaction is completed the setAutoCommit() method is called again and this time parameter true i.e. again activating the autocommit features.
All the statements belongs to transaction should be kept in a try block. So after all the statements call the commit() method. The rollback() method should be in the catch block to roll back if any exception occurs .
Suppose two lines in the try block are executed but in the third line exception occurs so it is caught by the catch block and the first two lines rolled back. So no statement executed.

Example:

Connection.setAutoCommit(false);
//these 4 queries should be transaction
Try{
Statement.executeUpdate(query1);
Statement.executeUpdate(query2);
Statement.executeUpdate(query3);
Statement.executeUpdate(query4);
Connection.commit();
System.out.println(“successfully completed”);
}//end of try block
catch(Exception e){
Connection.rollback();
System.out.println(“not success”);
}

No comments:

Post a Comment