Skip to lesson

commit and rollback in a try/catch

Money must never leave one account without reaching the other. A transaction only protects you if every path ends in a commit or a rollback, and the connection is handed back the way you found it.

The standard shape: work, commit, rollback in catch

The commit/rollback pattern is a try block that ends with commit(), a catch block that calls rollback() and rethrows, and a finally block that switches auto-commit back on.

Example 1 moves money between two wallets. A wallet here is a practice table made with CREATE TEMPORARY TABLE, which disappears when the connection closes, so the ShopLite tables stay untouched.

Java
conn.setAutoCommit(false);try {    // ... every statement of the action, on conn ...    conn.commit();} catch (SQLException | RuntimeException e) {    conn.rollback();    throw e;} finally {    conn.setAutoCommit(true);}
The standard transaction shape. setAutoCommit(false) starts it. The try block runs every statement on conn and ends with commit(). If any exception happens, the catch block calls rollback() and rethrows. Both paths end in the finally block, which restores auto-commit.

Example 1 · A wallet transfer: commit or roll back

Runs in: a Maven project with the MySQL driver and the ShopLite database

TransferDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class TransferDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    // A practice table that exists only for this connection and disappears when it closes    static void createWallets(Connection conn) throws SQLException {        try (Statement st = conn.createStatement()) {            st.executeUpdate("CREATE TEMPORARY TABLE wallets ("                    + "owner VARCHAR(20) PRIMARY KEY, "                    + "balance DECIMAL(10,2) NOT NULL CHECK (balance >= 0))");            st.executeUpdate("INSERT INTO wallets VALUES ('Asha', 2000.00), ('Ravi', 500.00)");        }    }
    static void addToBalance(Connection conn, String owner, BigDecimal amount) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "UPDATE wallets SET balance = balance + ? WHERE owner = ?")) {            ps.setBigDecimal(1, amount);            ps.setString(2, owner);            ps.executeUpdate();        }    }
    static void transfer(Connection conn, String from, String to, BigDecimal amount) throws SQLException {        conn.setAutoCommit(false);        try {            addToBalance(conn, to, amount);              // credit first            addToBalance(conn, from, amount.negate());   // debit: fails if balance would go below 0            conn.commit();            System.out.println("Sent Rs " + amount + " from " + from + " to " + to);        } catch (SQLException e) {            conn.rollback();            System.out.println("Transfer of Rs " + amount + " failed (error " + e.getErrorCode() + "), rolled back");        } finally {            conn.setAutoCommit(true);        }    }
    static void printBalances(Connection conn) throws SQLException {        try (Statement st = conn.createStatement();             ResultSet rs = st.executeQuery("SELECT owner, balance FROM wallets ORDER BY owner")) {            while (rs.next()) {                System.out.println("  " + rs.getString("owner") + ": Rs " + rs.getBigDecimal("balance"));            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection conn = connect()) {            createWallets(conn);            transfer(conn, "Asha", "Ravi", new BigDecimal("750.00"));            printBalances(conn);            transfer(conn, "Ravi", "Asha", new BigDecimal("5000.00"));            printBalances(conn);        }    }}
Output
Sent Rs 750.00 from Asha to Ravi
  Asha: Rs 1250.00
  Ravi: Rs 1250.00
Transfer of Rs 5000.00 failed (error 3819), rolled back
  Asha: Rs 1250.00
  Ravi: Rs 1250.00

What this code does

  • The first transfer passes both UPDATEs and commits. The second one credits Asha, then the debit breaks CHECK (balance >= 0) with error 3819, and rollback() removes the credit too.
  • Balances after the failure are exactly as before it. The credit goes first here on purpose, to show that the rollback really undoes a statement that had worked.

commit() is the last line of the try, so it runs only if every statement worked. rollback() in the catch undoes whatever part already ran. Rethrowing (throw e) tells the caller the action failed. In Example 1 a CHECK (balance >= 0) on the table rejects a debit bigger than the balance.

Fix the error

Fix the transaction shape

Each snippet misbehaves. Pick the line that replaces the highlighted one.

Round 1 of 2

The transfer must roll back when the debit fails.

conn.setAutoCommit(true);
try {
addToBalance(conn, to, amount);
addToBalance(conn, from, amount.negate());
conn.commit();
} catch (SQLException e) {
conn.rollback();
throw e;
}

Error

java.sql.SQLException: Can't call rollback when autocommit=true

Rolling back on any exception, not only SQLException

An unchecked exception is a RuntimeException or one of its subclasses, such as IllegalStateException. The compiler does not force you to catch it, and catch (SQLException e) does not see it.

A transfer can fail for reasons that are not SQL errors: a daily limit, a bad number, a NullPointerException. Example 2 refuses a transfer above a limit, with and without catching RuntimeException.

Example 2 · Trap: finally commits the half-done work

Runs in: a Maven project with the MySQL driver and the ShopLite database

AnyExceptionDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class AnyExceptionDemo {    static final BigDecimal DAILY_LIMIT = new BigDecimal("1000.00");
    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static void resetWallets(Connection conn) throws SQLException {        try (Statement st = conn.createStatement()) {            st.executeUpdate("DROP TEMPORARY TABLE IF EXISTS wallets");            st.executeUpdate("CREATE TEMPORARY TABLE wallets ("                    + "owner VARCHAR(20) PRIMARY KEY, "                    + "balance DECIMAL(10,2) NOT NULL CHECK (balance >= 0))");            st.executeUpdate("INSERT INTO wallets VALUES ('Asha', 2000.00), ('Ravi', 500.00)");        }    }
    static void addToBalance(Connection conn, String owner, BigDecimal amount) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "UPDATE wallets SET balance = balance + ? WHERE owner = ?")) {            ps.setBigDecimal(1, amount);            ps.setString(2, owner);            ps.executeUpdate();        }    }
    static void checkDailyLimit(BigDecimal amount) {        if (amount.compareTo(DAILY_LIMIT) > 0) {            throw new IllegalStateException("daily limit of Rs " + DAILY_LIMIT + " crossed");        }    }
    // BUG: only SQLException triggers a rollback    static void transferBuggy(Connection conn, String from, String to, BigDecimal amount) throws SQLException {        conn.setAutoCommit(false);        try {            addToBalance(conn, to, amount);            addToBalance(conn, from, amount.negate());            checkDailyLimit(amount);                      // throws IllegalStateException            conn.commit();        } catch (SQLException e) {            conn.rollback();            throw e;        } finally {            conn.setAutoCommit(true);        }    }
    // FIX: any exception triggers a rollback    static void transferFixed(Connection conn, String from, String to, BigDecimal amount) throws SQLException {        conn.setAutoCommit(false);        try {            addToBalance(conn, to, amount);            addToBalance(conn, from, amount.negate());            checkDailyLimit(amount);            conn.commit();        } catch (SQLException | RuntimeException e) {            conn.rollback();            throw e;        } finally {            conn.setAutoCommit(true);        }    }
    static String balances(Connection conn) throws SQLException {        StringBuilder sb = new StringBuilder();        try (Statement st = conn.createStatement();             ResultSet rs = st.executeQuery("SELECT owner, balance FROM wallets ORDER BY owner")) {            while (rs.next()) {                sb.append(rs.getString("owner")).append(" Rs ").append(rs.getBigDecimal("balance")).append("  ");            }        }        return sb.toString().trim();    }
    public static void main(String[] args) throws SQLException {        try (Connection conn = connect()) {            resetWallets(conn);            try {                transferBuggy(conn, "Asha", "Ravi", new BigDecimal("1500.00"));            } catch (IllegalStateException e) {                System.out.println("Buggy: transfer refused, " + e.getMessage());            }            System.out.println("Buggy: " + balances(conn));
            resetWallets(conn);            try {                transferFixed(conn, "Asha", "Ravi", new BigDecimal("1500.00"));            } catch (IllegalStateException e) {                System.out.println("Fixed: transfer refused, " + e.getMessage());            }            System.out.println("Fixed: " + balances(conn));        }    }}
Output
Buggy: transfer refused, daily limit of Rs 1000.00 crossed
Buggy: Asha Rs 500.00  Ravi Rs 2000.00
Fixed: transfer refused, daily limit of Rs 1000.00 crossed
Fixed: Asha Rs 2000.00  Ravi Rs 500.00

What this code does

  • In transferBuggy the IllegalStateException is not an SQLException, so there is no rollback. finally calls setAutoCommit(true), which commits the open transaction: Rs 1,500 moves although the transfer was refused.
  • transferFixed catches SQLException | RuntimeException, rolls back and rethrows. The balances stay at Rs 2000.00 and Rs 500.00.

The trap is worse than "no rollback". The exception flies past the catch, then finally calls setAutoCommit(true), and the JDBC rule is that switching auto-commit on commits the open transaction. So Example 2 moves Rs 1,500 although the transfer was refused. The fix is catch (SQLException | RuntimeException e). If rollback() itself fails, add that error to the original with e.addSuppressed(rollbackError) so neither is lost.

Predict the output

Is the debit saved?

The transfer is refused with an IllegalStateException after the debit ran. Is the debit kept?

Round 1 of 2

Only SQLException is caught.

conn.setAutoCommit(false);
try {
addToBalance(conn, from, amount.negate());
checkDailyLimit(amount); // throws IllegalStateException
addToBalance(conn, to, amount);
conn.commit();
} catch (SQLException e) {
conn.rollback();
throw e;
} finally {
conn.setAutoCommit(true);
}
Rule of thumb: by the time finally runs, the transaction must already be committed or rolled back.

Restoring auto-commit before the connection is reused

A connection often outlives one method. Example 3 shows a transfer that leaves auto-commit off, and the next method, which expects its UPDATE to save at once.

Example 3 · Leaving auto-commit off loses the next change

Runs in: a Maven project with the MySQL driver and the ShopLite database

RestoreAutoCommitDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class RestoreAutoCommitDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static void createWallets(Connection conn) throws SQLException {        try (Statement st = conn.createStatement()) {            st.executeUpdate("CREATE TEMPORARY TABLE wallets ("                    + "owner VARCHAR(20) PRIMARY KEY, "                    + "balance DECIMAL(10,2) NOT NULL CHECK (balance >= 0))");            st.executeUpdate("INSERT INTO wallets VALUES ('Asha', 2000.00), ('Ravi', 500.00)");        }    }
    static void addToBalance(Connection conn, String owner, BigDecimal amount) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "UPDATE wallets SET balance = balance + ? WHERE owner = ?")) {            ps.setBigDecimal(1, amount);            ps.setString(2, owner);            ps.executeUpdate();        }    }
    static void transfer(Connection conn, String from, String to, BigDecimal amount, boolean restore)            throws SQLException {        boolean oldAutoCommit = conn.getAutoCommit();   // remember the caller's setting        conn.setAutoCommit(false);        try {            addToBalance(conn, to, amount);            addToBalance(conn, from, amount.negate());            conn.commit();        } catch (SQLException | RuntimeException e) {            conn.rollback();            throw e;        } finally {            if (restore) {                conn.setAutoCommit(oldAutoCommit);      // hand the connection back as we got it            }        }    }
    // Written by someone who expects auto-commit to be on    static void setPrice(Connection conn, int productId, BigDecimal price) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "UPDATE products SET price = ? WHERE product_id = ?")) {            ps.setBigDecimal(1, price);            ps.setInt(2, productId);            ps.executeUpdate();        }    }
    static BigDecimal priceOf(int productId) throws SQLException {        try (Connection conn = connect();             PreparedStatement ps = conn.prepareStatement("SELECT price FROM products WHERE product_id = ?")) {            ps.setInt(1, productId);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getBigDecimal("price");            }        }    }
    static void run(boolean restore) throws SQLException {        int pragmaticProgrammer = 10;        try (Connection conn = connect()) {            createWallets(conn);            transfer(conn, "Asha", "Ravi", new BigDecimal("300.00"), restore);            setPrice(conn, pragmaticProgrammer, new BigDecimal("699.00"));        }        String label = restore ? "Auto-commit restored:" : "Auto-commit left off:";        System.out.println(label + " saved price = Rs " + priceOf(pragmaticProgrammer));    }
    public static void main(String[] args) throws SQLException {        run(false);        run(true);
        try (Connection conn = connect()) {            setPrice(conn, 10, new BigDecimal("650.00"));        }    }}
Output
Auto-commit left off: saved price = Rs 650.00
Auto-commit restored: saved price = Rs 699.00

What this code does

  • With restore false, transfer returns with auto-commit still off. setPrice expects its UPDATE to save at once, but it is never committed and is lost on close: the saved price stays 650.00.
  • With restore true, finally puts back the old setting (true), so the UPDATE commits and the price is 699.00. The program sets the price back to 650.00 at the end.

A connection pool (a shared set of ready connections) hands the same connection to many parts of the app, so the next user inherits a transaction they did not ask for: in Example 3 the price change is never committed and is lost when the connection closes. Remember the old value with getAutoCommit() at the start and put it back in finally. Then your method works the same whether the caller had auto-commit on or off.

Find the bug

Find the restore bug

Each method should give the connection back as it got it. Tap the wrong line.

Put back what the caller had.

Round 1 of 3

Savepoints: rolling back part of a transaction

A savepoint is a named marker inside a transaction. conn.rollback(savepoint) undoes only the work done after that marker; everything before it stays in the transaction, waiting for commit().

Use a savepoint for an optional step. Example 4 buys a book, then offers a mouse as an add-on, but the mouse is out of stock.

Java
Savepoint beforeAddOn = conn.setSavepoint("add_on");try {    addItem(conn, orderId, 8, 1, price);   // optional step} catch (SQLException e) {    conn.rollback(beforeAddOn);            // undo only the add-on}conn.commit();                             // the rest is saved

Example 4 · A savepoint skips an add-on but keeps the order

Runs in: a Maven project with the MySQL driver and the ShopLite database

SavepointDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Savepoint;import java.sql.Statement;
public class SavepointDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static int insertOrder(Connection conn, int customerId, int addressId) throws SQLException {        String sql = "INSERT INTO orders (customer_id, address_id) VALUES (?, ?)";        try (PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {            ps.setInt(1, customerId);            ps.setInt(2, addressId);            ps.executeUpdate();            try (ResultSet keys = ps.getGeneratedKeys()) {                keys.next();                return keys.getInt(1);            }        }    }
    // Inserts the item row and takes the units out of stock    static void addItem(Connection conn, int orderId, int productId, int qty, BigDecimal price) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?)")) {            ps.setInt(1, orderId);            ps.setInt(2, productId);            ps.setInt(3, qty);            ps.setBigDecimal(4, price);            ps.executeUpdate();        }        try (PreparedStatement ps = conn.prepareStatement(                "UPDATE products SET stock = stock - ? WHERE product_id = ?")) {            ps.setInt(1, qty);            ps.setInt(2, productId);            ps.executeUpdate();   // CHECK (stock >= 0) fails when there is not enough stock        }    }
    static int countItems(Connection conn, int orderId) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("SELECT COUNT(*) FROM order_items WHERE order_id = ?")) {            ps.setInt(1, orderId);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt(1);            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection conn = connect()) {            conn.setAutoCommit(false);            try {                int orderId = insertOrder(conn, 5, 6);                addItem(conn, orderId, 10, 1, new BigDecimal("650.00"));     // The Pragmatic Programmer
                Savepoint beforeAddOn = conn.setSavepoint("add_on");                try {                    addItem(conn, orderId, 8, 1, new BigDecimal("849.00"));                    System.out.println("Add-on added");                } catch (SQLException e) {                    conn.rollback(beforeAddOn);                    System.out.println("Add-on skipped: error " + e.getErrorCode()                            + ", rolled back to " + beforeAddOn.getSavepointName());                }
                conn.commit();                System.out.println("Order committed with " + countItems(conn, orderId) + " item(s)");            } catch (SQLException | RuntimeException e) {                conn.rollback();                throw e;            } finally {                conn.setAutoCommit(true);            }        }    }}
Output
Add-on skipped: error 3819, rolled back to add_on
Order committed with 1 item(s)

What this code does

  • The book line is added before the savepoint. The mouse line is added after it; reducing the mouse stock from 0 breaks CHECK (stock >= 0) with error 3819.
  • rollback(beforeAddOn) removes only the mouse item row. commit() then saves the order with one item, and the outer catch would still roll back everything for any other error.

Create one with conn.setSavepoint("name") (or setSavepoint() without a name), and remove it with releaseSavepoint(sp) when you no longer need it. A savepoint only works with auto-commit off, and after rollback(sp1) every savepoint made after sp1 is gone too.

Predict the output

Which rows are saved?

Auto-commit is off. Name the rows that exist after commit().

Round 1 of 2

Rollback to a savepoint.

insertRow(conn, "A");
Savepoint sp = conn.setSavepoint();
insertRow(conn, "B");
conn.rollback(sp);
insertRow(conn, "C");
conn.commit();

Next step

Check your understanding

11 quick questions