Friday 13 July 2018

MySQL JDBC Transaction

MySQL JDBC Transaction?

In this tutorial, you will learn how to use commit() and rollback() methods of the Connection object to control transaction.

Setting auto-commit mode

When you connect to MySQL databases, the auto-commit mode is set to true by default. It means that the changes will be applied to the database once the statement successfully executed. In case you want to control when to commit the transaction, you call the setAutoCommit() method of the Connectionobject as follows:
Once you have set auto-commit mode to false , you can call commit() or rollback() methods of the Connection object to commit or rollback the transaction.
Notice that you should always call setAutoCommit() method right after you open a connection to the database.

Committing and rolling back a transaction

Once the auto-commit mode is set to false , you can commit or rollback the transaction. The flow of using those methods is as follows:

MySQL JDBC transaction example

In this example, we will insert a new record into the candidates table and also assign some of skills to the newly inserted candidate.

We will perform both inserting a candidate and assigning skills within one transaction. The steps will be as follows:
  1. Insert a record into the candidates table and get the inserted ID back.
  2. Insert a set of candidate ID and Skill ID into the candidate_skills table.
  3. If all above operations are successfully, commit the transaction, otherwise roll it back.
The following is the complete example of using JDBC transaction.
Let’s check the table candidates table before we run the program.

Now, we run the program.

and check the candidates table again:

and check also the candidate_skills table to see if the assignments are there.
candidate_skills table
As you see we have successfully inserted data into both candidates and candidate_skills table within the same transaction.

0 comments:

Post a Comment