Java Reference
In-Depth Information
13-7. Performing Transactions
Problem
The way in which your application is structured requires a sequential processing of
tasks. One task depends on another, and each process performs a different database ac-
tion. If one of the tasks along the way fails, the database processing that has already oc-
curred needs to be reversed.
Solution
Set your
Connection
object auto-commit to false and then perform the transactions
you want to complete. Once you've successfully performed each of the transactions,
manually commit the
Connection
object; otherwise, roll back each of the transac-
tions that have taken place. The following code example demonstrates transaction man-
agement. If you look at the
main()
method of the
TransactionExample
class,
you will see that the
Connection
object's
autoCommit()
preference has been set
to false, and then the database transactions are performed. If all the transactions are
successful, the
Connection
object is manually committed by calling the
commit()
method; otherwise, all the transactions are rolled back by calling the
rollback()
method.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import
org.java8recipes.chapter13.recipe13_01.CreateConnection;
public class TransactionExample {
public static Connection conn = null;
public static void main(String[] args) {
boolean successFlag = false;
try {
CreateConnection createConn = new
CreateConnection();