Transactions with JDBC

Transactions with JDBC

Transactions JDBC
Transactions should have ACID properties. In a transaction, all the operations on the database should succeed; even one operation fails, all the operations in the transaction should be rolled back. This is the motto of Transactions JDBC.

Think there is a transaction where a cheque is credited (amount added to my bank account) and a cheque given by me to some party is to be debited (amount deducted). If the credit operation fails, the debit should not take place. That is, both should get succeeded or failed. This is how to do in JDBC.

Let us apply the above idea to our Employee table. I would like to insert a record, update a record and delete a record. Either all should be executed or even one fails all operations to be aborted (rolled back). Observe the following code.

The above 3 statements are without transactions applied. The disadvantage is even 103 record is not deleted insert and update operations will proceed.

Let us write the above three statements with transaction success guaranteed code.

Observe the following operations on Transactions JDBC

The best place for close operations is finally block. In realtime, the Hibernate framework takes care of all this along with connection pooling and cache mechanisms.


First do not allow any auto commit transactions. For this reason, set the auto commit to false.


If no SQLException (handled by super class Exception) is raised, all the operations are committed.


If any one fails, all are aborted with rollback() method in catch block. Observe, commit() is called at the end of all the operations.

Leave a Reply

Your email address will not be published. Required fields are marked *