← Back to Chapters

JDBC Transactions

? JDBC Transactions

? Quick Overview

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.

? Key Concepts

  • Auto-commit mode
  • Commit and Rollback
  • Atomicity and consistency
  • Savepoints
  • Transaction boundaries

? Syntax / Theory

By default, JDBC connections operate in auto-commit mode. To manage transactions manually, auto-commit must be disabled using setAutoCommit(false).

? Code Example(s)

? View Code Example
// 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();

? Interactive Simulation

Scenario: Transfer $1000 from Amit to Ravi.
Observe how Rollback restores original values if an error occurs.

> Ready for transaction...

? Live Output / Explanation

Transaction Behavior

If both insert operations execute successfully, the data is permanently saved. If an error occurs before commit(), no data is stored in the database.

? Tips & Best Practices

  • Always disable auto-commit for complex operations
  • Use rollback() inside catch blocks
  • Close connections in finally blocks
  • Prefer PreparedStatement for real applications

? Try It Yourself

  • Add a rollback when an exception occurs
  • Use Savepoint to partially rollback a transaction
  • Test transaction failure scenarios