JDBC Transaction


Transaction is a process of performing multiple database operation as one unit with all nothing criteria i.e when all the database operation in that unit is successful then transaction will be successful.


  • When an one operation of that unit will fail then transaction will be fail.
  • when transaction will successful then you have to issue commit.
  • When transaction is failed then you have to issue rollback to cancel all the operations.
  • To implement transaction properly in your application it guarantee ACID property.
                                A ---- Automicity
                                C-----Consistency
                                I------Isolation
                                D-----Durability 
  • By default commit will be issued JDBC connection at the end of every SQL opertation.
  • When commit is issued for every SQL statement you can't cancel the operations when something goes wrong.
  • If you want to perform multiple operation as one transaction first you have to disable the auto commit as follows------
                            con.setAutoCommit(false);
                            This is the beginning of transaction.
  •   After starting the transaction you can do multiple database operation as per your requirement.
         

                        try{
                               con.setAutoCommit(false);
                                     op1;
                                     op2;
                                     ---
                                     ---
                                    op10
                         }

                    catch(SQLException e){
                   con.rollback();

                   }
  • Whenever transaction is ended either by commit or rollback then immediately auto commit will turn on.