JDBC Transaction Rollback Example (original) (raw)

In this example will talk about how to perform rollback in JDBC transactions.

When we are making changes in the database through a java.sql.Connection, it’s necessary prevent it form going to an inconsistent state, in case of an exception for example. So how do we do that? There are some key steps.

It’s so important that you remember that if you call connection.commit() the changes cannot be reverted with connection.rollback().

Let’s take a look of the example with this code snippet.

DBConnection.java:

package com.javacodegeeks.jdbc.transactions;

import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;

/**

}

Rollback.java:

package com.javacodegeeks.jdbc.transactions;

import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;

/**

}

2. The Output

In this example, we define a column with a VARCHAR(6). This means that we can store up to six characters to it. In the first insert, we put "Malaga", whose length is within the limit. This will be stored in the database, but remember that the change is not still permanent. In the second insert we put in "Barcelona", whose length exceeds the limit. So it generates a SQLException thus connection.rollback(); is called.

This is the output.

The connection is successfully obtained The autocommit was disabled! Data truncation: Data too long for column 'name' at row 1 The transaction rollback

Now if you go to your database you will see that "Malaga" is not inserted to the table, because the transaction rolled back. So all the changes that have not been committed will be reverted.

3. Download Source Code

Photo of Andres Cespedes

Andres is a Java Software Craftsman from Medellin Colombia, who strongly develops on DevOps practices, RESTful Web Services, Continuous integration and delivery. Andres is working to improve software process and modernizing software culture on Colombia.