The goal of this tutorial is to understand how to manage transactions in Java Database Connectivity (JDBC). Transactions are a vital part of any database operation and JDBC provides robust functionalities to handle them efficiently.
By the end of this tutorial, you'll learn:
Prerequisites:
A transaction is a logical unit of work that contains one or more SQL statements. It ensures the integrity of data by making sure all operations within the transaction are executed or none at all (Atomicity). If any statement fails, the changes are rolled back to maintain consistency.
By default, JDBC auto-commits each SQL statement immediately after it is executed. However, we can manage transactions manually by disabling this auto-commit feature.
setAutoCommit(false)
.commit()
.rollback()
.try (Connection con = DriverManager.getConnection(url, username, password)) {
// Begin transaction
con.setAutoCommit(false);
try (Statement stmt = con.createStatement()) {
// Perform operations
stmt.executeUpdate("INSERT INTO students VALUES (1, 'John')");
stmt.executeUpdate("INSERT INTO students VALUES (2, 'Jane')");
// Commit transaction
con.commit();
} catch (SQLException e) {
// Handle failure
con.rollback();
e.printStackTrace();
}
}
try (Connection con = DriverManager.getConnection(url, username, password)) {
// Begin transaction
con.setAutoCommit(false);
try (Statement stmt = con.createStatement()) {
// Perform operations
stmt.executeUpdate("INSERT INTO students VALUES (1, 'John')");
stmt.executeUpdate("INSERT INTO nonexistent_table VALUES (2, 'Jane')"); // This will fail
// Commit transaction
con.commit();
} catch (SQLException e) {
// Handle failure
con.rollback(); // Rollback changes since the second insert failed
e.printStackTrace();
}
}
In this tutorial, we've learned about transaction management in JDBC, how to execute a set of SQL statements as a single unit of work, and handle failures. For further learning, consider exploring savepoints in JDBC, which allow you to roll back to a certain point in a transaction, instead of the whole transaction.
Happy learning and coding! For any doubts, refer to the official JDBC documentation.