Auto-commit and turning it off
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A customer pays for an order, but the stock update fails halfway. By default JDBC saves every statement the moment it runs, so the shop is left with half an order. How do several statements succeed or fail together?
Auto-commit: every statement is its own transaction
Auto-commit is the default JDBC mode in which the driver commits every statement as soon as it finishes, so each statement is its own tiny transaction.
Every new Connection starts with auto-commit on. Example 1 changes the stock of the book Clean Code, then tries to undo it.
Example 1 · Auto-commit: saved at once, nothing to roll back
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class AutoCommitDemo { static Connection connect() throws SQLException { return DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); }
static int stockOf(Connection conn, int productId) throws SQLException { try (PreparedStatement ps = conn.prepareStatement( "SELECT stock FROM products WHERE product_id = ?")) { ps.setInt(1, productId); try (ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getInt("stock"); } } }
static void changeStock(Connection conn, int productId, int change) throws SQLException { try (PreparedStatement ps = conn.prepareStatement( "UPDATE products SET stock = stock + ? WHERE product_id = ?")) { ps.setInt(1, change); ps.setInt(2, productId); ps.executeUpdate(); } }
public static void main(String[] args) throws SQLException { int cleanCode = 9; // product 9 is the book "Clean Code" try (Connection writer = connect(); Connection reader = connect()) { System.out.println("Auto-commit on a new connection: " + writer.getAutoCommit()); System.out.println("Stock before: " + stockOf(reader, cleanCode));
changeStock(writer, cleanCode, -1); // committed as soon as it finishes System.out.println("Another connection sees: " + stockOf(reader, cleanCode));
try { writer.rollback(); // too late: there is nothing to undo } catch (SQLException e) { System.out.println("rollback() failed: " + e.getMessage()); }
changeStock(writer, cleanCode, +1); System.out.println("Stock after putting it back: " + stockOf(reader, cleanCode)); } }}Auto-commit on a new connection: true Stock before: 30 Another connection sees: 29 rollback() failed: Can't call rollback when autocommit=true Stock after putting it back: 30
What this code does
- The
writerconnection changes the stock and the separatereaderconnection sees 29 straight away, because auto-commit already committed the UPDATE. rollback()on an auto-commit connection throwsSQLException: Can't call rollback when autocommit=true. The program puts the book back with a second UPDATE so it gives the same output every run.
For one-statement jobs this is what you want: a product search or a single price change needs nothing more, and every other connection sees the change straight away. The flip side is that nothing is left to undo, so rollback() fails with Can't call rollback when autocommit=true, because no open transaction exists.
A half-finished order when the second statement fails
A transaction is a group of SQL statements that is saved completely or not at all. If one statement fails, the changes of the others are undone as well.
Placing an order needs two INSERTs: one row in orders, then one row per product in order_items. Example 2 uses product id 99, which does not exist, so the second INSERT fails.
Example 2 · Auto-commit leaves an order with no items
Runs in: a Maven project with the MySQL driver and the ShopLite database
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 HalfFinishedOrderDemo { 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); } } }
static void insertItem(Connection conn, int orderId, int productId, int quantity, BigDecimal unitPrice) throws SQLException { String sql = "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?)"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setInt(1, orderId); ps.setInt(2, productId); ps.setInt(3, quantity); ps.setBigDecimal(4, unitPrice); ps.executeUpdate(); } }
static int count(Connection conn, String table) throws SQLException { try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM " + table)) { rs.next(); return rs.getInt(1); } }
public static void main(String[] args) throws SQLException { try (Connection conn = connect()) { // auto-commit is on int ordersBefore = count(conn, "orders"); int itemsBefore = count(conn, "order_items");
try { int orderId = insertOrder(conn, 1, 1); // statement 1: works, committed System.out.println("Order row inserted"); insertItem(conn, orderId, 99, 1, new BigDecimal("499.00")); // no product 99 System.out.println("Item row inserted"); } catch (SQLException e) { System.out.println("Item insert failed: error " + e.getErrorCode()); }
System.out.println("New rows in orders: " + (count(conn, "orders") - ordersBefore)); System.out.println("New rows in order_items: " + (count(conn, "order_items") - itemsBefore)); } }}Order row inserted Item insert failed: error 1452 New rows in orders: 1 New rows in order_items: 0
What this code does
- The order INSERT is committed before the item INSERT runs. When the item fails (error 1452: product 99 does not exist), the order row is already permanent.
- The program prints how many rows were added, not the total, so you get the same lines each run. Each run does leave one more empty order in
orders.
With auto-commit on, the order row is saved before the item INSERT even starts, so MySQL error 1452 (a foreign key check) leaves an order with no items. A customer sees an empty order, and reports count a sale that never happened. Each statement is safe on its own, but a business action made of several statements can stop halfway.
Predict the output
How many rows are left?
The second INSERT fails every time (no product 99). Count the new rows in orders.
Round 1 of 3
Auto-commit is on (the default).
setAutoCommit(false) to group statements
commit() makes every change since the last commit permanent and visible to other connections. Its partner rollback() throws those changes away.
conn.setAutoCommit(false) starts manual mode: the statements you run next form one transaction. Example 3 places a good order and a bad one.
conn.setAutoCommit(false); // start groupingtry { int orderId = insertOrder(conn, 1, 1); insertItem(conn, orderId, productId, 1, price); conn.commit(); // both rows, permanently} catch (SQLException e) { conn.rollback(); // neither row}Example 3 · setAutoCommit(false): both rows or neither
Runs in: a Maven project with the MySQL driver and the ShopLite database
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 GroupedOrderDemo { 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); } } }
static void insertItem(Connection conn, int orderId, int productId, int quantity, BigDecimal unitPrice) throws SQLException { String sql = "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?)"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setInt(1, orderId); ps.setInt(2, productId); ps.setInt(3, quantity); ps.setBigDecimal(4, unitPrice); ps.executeUpdate(); } }
static int count(Connection conn, String table) throws SQLException { try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM " + table)) { rs.next(); return rs.getInt(1); } }
static void placeOrder(Connection conn, int productId, BigDecimal price) throws SQLException { int ordersBefore = count(conn, "orders"); conn.setAutoCommit(false); // from here on, nothing is saved until commit() try { int orderId = insertOrder(conn, 1, 1); insertItem(conn, orderId, productId, 1, price); conn.commit(); // both rows become permanent together System.out.println("Product " + productId + ": committed"); } catch (SQLException e) { conn.rollback(); // both rows disappear together System.out.println("Product " + productId + ": error " + e.getErrorCode() + ", rolled back"); } finally { conn.setAutoCommit(true); } System.out.println(" new rows in orders: " + (count(conn, "orders") - ordersBefore)); }
public static void main(String[] args) throws SQLException { try (Connection conn = connect()) { placeOrder(conn, 9, new BigDecimal("499.00")); placeOrder(conn, 99, new BigDecimal("499.00")); } }}Product 9: committed new rows in orders: 1 Product 99: error 1452, rolled back new rows in orders: 0
What this code does
- For product 9 both INSERTs work and
commit()makes them permanent together: one new order row. - For product 99 the item fails,
rollback()removes the order row too, so no new order row is left.setAutoCommit(true)infinallygives the connection back in its normal mode.
Nothing is permanent until commit(). If something fails, rollback() throws away every change since the last commit, so the order and its items are saved together or not at all: in Example 3 the good order adds one row, and the bad order leaves nothing behind. The example also switches auto-commit back on in a finally block; the next lesson explains why.
Order of execution
Put the grouped order in sequence
Arrange the steps of an order saved as one transaction, from first to last.
What happens to uncommitted work when the connection closes
Example 4 reduces a stock in a transaction but never commits. The writer sees its own new value (25), while a second connection still sees 30.
Example 4 · Closing without commit throws the change away
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class CloseWithoutCommitDemo { static Connection connect() throws SQLException { return DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); }
static int stockOf(Connection conn, int productId) throws SQLException { try (PreparedStatement ps = conn.prepareStatement( "SELECT stock FROM products WHERE product_id = ?")) { ps.setInt(1, productId); try (ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getInt("stock"); } } }
public static void main(String[] args) throws SQLException { int cleanCode = 9; try (Connection reader = connect()) { System.out.println("Stock at the start: " + stockOf(reader, cleanCode));
try (Connection writer = connect()) { writer.setAutoCommit(false); try (PreparedStatement ps = writer.prepareStatement( "UPDATE products SET stock = stock - 5 WHERE product_id = ?")) { ps.setInt(1, cleanCode); ps.executeUpdate(); } System.out.println("Writer sees: " + stockOf(writer, cleanCode)); System.out.println("Reader sees: " + stockOf(reader, cleanCode)); // no commit() and no rollback(): the connection just closes here }
System.out.println("After close: " + stockOf(reader, cleanCode)); } }}Stock at the start: 30 Writer sees: 25 Reader sees: 30 After close: 30
What this code does
- Inside its own transaction the writer sees 25. The reader, a different connection, still sees the committed value 30.
- The writer's try-with-resources block closes the connection without
commit(). MySQL rolls the open transaction back, so the stock is still 30 afterwards.
Work you have not committed is not visible to other connections. If the connection closes without commit() or rollback(), MySQL throws the open transaction away, as if you had called rollback(), so the stock stays 30. Do not rely on that: the JDBC specification leaves this case to the driver, and some drivers (Oracle's, by default) commit instead. Always end a transaction yourself.
One transaction means one connection
A transaction belongs to one connection: commit() and rollback() only affect statements that ran on that same Connection object. In Example 5 a helper opens its own.
Example 5 · A helper with its own connection breaks the rollback
Runs in: a Maven project with the MySQL driver and the ShopLite database
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 OneConnectionDemo { static Connection connect() throws SQLException { return DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); }
// BUG: opens its own connection, so the insert is committed at once static int insertOrderOwnConnection(int customerId, int addressId) throws SQLException { try (Connection own = connect()) { return insertOrder(own, customerId, addressId); } }
// FIX: uses the connection the caller passes in 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); } } }
static void insertItem(Connection conn, int orderId, int productId, int quantity, BigDecimal unitPrice) throws SQLException { String sql = "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?)"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setInt(1, orderId); ps.setInt(2, productId); ps.setInt(3, quantity); ps.setBigDecimal(4, unitPrice); ps.executeUpdate(); } }
static int countOrders(Connection conn) throws SQLException { try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM orders")) { rs.next(); return rs.getInt(1); } }
static void tryOrder(Connection conn, boolean shareConnection) throws SQLException { int before = countOrders(conn); conn.setAutoCommit(false); try { int orderId = shareConnection ? insertOrder(conn, 1, 1) : insertOrderOwnConnection(1, 1); insertItem(conn, orderId, 99, 1, new BigDecimal("499.00")); // fails: no product 99 conn.commit(); } catch (SQLException e) { conn.rollback(); } finally { conn.setAutoCommit(true); } String label = shareConnection ? "One shared connection" : "Helper with its own connection"; System.out.println(label + ": orders left after rollback = " + (countOrders(conn) - before)); }
public static void main(String[] args) throws SQLException { try (Connection conn = connect()) { tryOrder(conn, false); tryOrder(conn, true); } }}Helper with its own connection: orders left after rollback = 1 One shared connection: orders left after rollback = 0
What this code does
insertOrderOwnConnectionopens a second connection in auto-commit mode, so its INSERT is saved at once.conn.rollback()cannot touch it, and one order row is left behind.insertOrder(conn, ...)runs on the caller's connection. Now the rollback removes the order row too: 0 rows left.
A helper with its own connection runs in auto-commit mode, so its INSERT is saved at once and the order row stays even after the caller rolls back. Pass the Connection into every method that is part of the transaction. A helper with its own connection can also wait forever on a row that your main connection has locked.
Find the bug
Find the transaction bug
Each snippet should save the work safely. Tap the wrong line, then check the fix.
The order row and its items must roll back together.
Round 1 of 4Next step
Check your understanding
11 quick questions