← Back to Chapters

Commit & Rollback

? Commit & Rollback in Advance Java

? Quick Overview

In Advance Java, commit and rollback are used in JDBC transactions to control how database changes are permanently saved or undone. They ensure data consistency and atomic operations.

? Key Concepts

  • Transaction = group of SQL statements executed as a single unit
  • commit() saves all changes permanently
  • rollback() cancels all changes since last commit
  • setAutoCommit(false) enables manual transaction control

? Syntax / Theory

By default, JDBC works in auto-commit mode. To use commit and rollback, auto-commit must be disabled.

? View Code Example
// Disable auto-commit to start a manual transaction
connection.setAutoCommit(false);

// Save all changes permanently
connection.commit();

// Undo all changes since last commit
connection.rollback();

? Interactive Lab: Transaction Simulator

Simulate a bank transfer. Watch how data becomes "Pending" before you decide to Save (Commit) or Undo (Rollback).

? User A $1000
➡️
? User B $500
Current State: Auto-Commit ON (Default)

? Code Example(s)

The following example demonstrates transferring money between two accounts safely.

? View Code Example
// JDBC transaction example using commit and rollback
Connection con = DriverManager.getConnection(url, user, pass);

// Disable auto-commit mode
con.setAutoCommit(false);

PreparedStatement ps1 = con.prepareStatement(
"UPDATE account SET balance = balance - 1000 WHERE id = 1");

PreparedStatement ps2 = con.prepareStatement(
"UPDATE account SET balance = balance + 1000 WHERE id = 2");

ps1.executeUpdate();
ps2.executeUpdate();

// Commit transaction if both queries succeed
con.commit();

? Live Output / Explanation

What Happens?

  • If both SQL updates succeed → money transfer is saved
  • If any query fails → rollback can be executed
  • Database remains consistent at all times

✅ Tips & Best Practices

  • Always disable auto-commit before using transactions
  • Use try-catch blocks to handle rollback safely
  • Commit only after all queries succeed
  • Rollback inside catch block on errors

? Try It Yourself

  • Create a JDBC program using commit and rollback
  • Force an exception and observe rollback behavior
  • Test with multiple update queries