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.
commit() saves all changes permanentlyrollback() cancels all changes since last commitsetAutoCommit(false) enables manual transaction controlBy default, JDBC works in auto-commit mode. To use commit and rollback, auto-commit must be disabled.
// 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();
Simulate a bank transfer. Watch how data becomes "Pending" before you decide to Save (Commit) or Undo (Rollback).
The following example demonstrates transferring money between two accounts safely.
// 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();