JDBC Transactions allow you to execute multiple SQL statements as a single logical unit of work. If any statement fails, the entire transaction can be rolled back to maintain data consistency.
By default, JDBC connections operate in auto-commit mode. To manage transactions manually, auto-commit must be disabled using setAutoCommit(false).
// Disable auto-commit to start a transaction
Connection con = DriverManager.getConnection(url, user, pass);
con.setAutoCommit(false);
// Create statement object
Statement stmt = con.createStatement();
// Execute multiple SQL statements
stmt.executeUpdate("INSERT INTO account VALUES (1, 'Amit', 5000)");
stmt.executeUpdate("INSERT INTO account VALUES (2, 'Ravi', 7000)");
// Commit transaction if all statements succeed
con.commit();
// Close resources
stmt.close();
con.close();
Scenario: Transfer $1000 from Amit to Ravi.
Observe how Rollback restores original values if an error occurs.
If both insert operations execute successfully, the data is permanently saved. If an error occurs before commit(), no data is stored in the database.
rollback() inside catch blocks