Commit or Roll Back a Unit of Work
Core idea
A transaction groups changes so they can be committed together or rolled back together. With Python 3.12+ autocommit=False, sqlite3 opens a transaction and opens another after commit or rollback. The connection context manager commits when a block exits successfully and rolls back when an exception escapes it. It does not close the connection; closing handles that separately.
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE bins (code TEXT, qty INTEGER)') db.executemany('INSERT INTO bins VALUES (?,?)', [('A',5),('B',1)]) db.commit() with db: db.execute("UPDATE bins SET qty=qty-2 WHERE code='A'") db.execute("UPDATE bins SET qty=qty+2 WHERE code='B'") print(db.execute('SELECT qty FROM bins ORDER BY code').fetchall())Both updates complete inside the same transaction. The total stays six.
Roll back a rejected change
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE bins (qty INTEGER CHECK(qty >= 0))') db.execute('INSERT INTO bins VALUES (5)') db.commit() try: with db: db.execute('UPDATE bins SET qty=3') db.execute('UPDATE bins SET qty=-1') except sqlite3.IntegrityError: print('rejected') print(db.execute('SELECT qty FROM bins').fetchone()[0])The failing constraint lets the exception escape the transaction block. The earlier update is also undone.
Common mistake
Catching an error inside with db and then exiting normally can commit earlier changes. Catch outside the transaction or explicitly roll back as appropriate. With autocommit=True, this context manager does not create an atomic multi-statement unit.
Practice
Add a third update that violates a CHECK constraint. Verify all changes in that unit are undone, then repeat with valid values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Transactions
Check your understanding of transactions.
What is printed?
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE t(n)') db.commit() db.execute('INSERT INTO t VALUES (1)') db.rollback() print(db.execute('SELECT count(*) FROM t').fetchone()[0])What is printed?
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE t(n)') db.commit() with db: db.execute('INSERT INTO t VALUES (2)') db.rollback() print(db.execute('SELECT n FROM t').fetchone()[0])Where should the example catch a transaction failure?
Does with db close a SQLite connection?