Skip to main content

How to Commit or Roll Back SQLite Changes in Python with a with Block

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

Some changes belong together: take points from one member and give them to another, or add an order and its items. If the second step fails, the first must not stay. A with connection: block gives you that: it commits everything when the block succeeds and rolls everything back when it fails. This guide runs one block that works and one that fails halfway, with real output from Python 3.15.2.

Syntax​

Syntax
with connection:
connection.execute("<first change>")
connection.execute("<second change>")
PartWhat it means
with connection:Starts the block. The changes inside it form one transaction
End of the block, no errorsqlite3 commits the changes
An exception inside the blocksqlite3 rolls the changes back, then the exception carries on

Python's sqlite3 documentation: "If the body of the with statement finishes without exceptions, the transaction is committed. If this commit fails, or if the body of the with statement raises an uncaught exception, the transaction is rolled back."

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

The table of members has the name as its primary key, so the same name can't be added twice:

with_connection.py
import sqlite3

connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE members (name TEXT PRIMARY KEY, points INTEGER)")

with connection:
connection.execute("INSERT INTO members VALUES ('Ana', 100)")
print("After the first block:", connection.execute("SELECT * FROM members").fetchall())

try:
with connection:
connection.execute("INSERT INTO members VALUES ('Ben', 50)")
connection.execute("INSERT INTO members VALUES ('Ana', 20)")
except sqlite3.IntegrityError as error:
print("Rolled back:", error)
print("After the second block:", connection.execute("SELECT * FROM members").fetchall())

connection.close()

The with_connection.py script in a macOS-style code window: a first with connection block inserts Ana, then a second block inside try inserts Ben and Ana again, and the IntegrityError is caught outside the block before the members are printed again.

  • The first block inserts Ana and ends normally.
  • The second block inserts Ben, then tries to insert Ana again, which breaks the primary key.
  • The try and except sit outside the with block, so the error leaves the block first.

Step 2: Run It​

Terminal
uv run python with_connection.py
Output
After the first block: [('Ana', 100)]
Rolled back: UNIQUE constraint failed: members.name
After the second block: [('Ana', 100)]

The output in a terminal: after the first block the table holds Ana with 100, the second block was rolled back with UNIQUE constraint failed: members.name, and after it the table still holds only Ana with 100.

The first block was committed: Ana is there. The second block failed on its second insert, and Ben, whose insert had worked, is gone too: the whole block was rolled back. Then the IntegrityError carried on out of the block, where the except printed it.

Common Mistakes​

MistakeWhat happensDo this instead
Catching the error inside the with blockThe block ends without an exception, so it commits: Ben is saved even though Ana's insert failedLet the error leave the block, and catch it outside
Expecting with connection: to close the connectionIt stays open: the script above queries it after both blocksCall connection.close() when you're done
Using with connection: after close()sqlite3.ProgrammingError: Cannot operate on a closed database.Use the block while the connection is open

Troubleshooting​

SymptomLikely causeFix
Part of a failed block's changes stayed in the databaseThe exception was caught inside the blockMove the try outside the with

FAQ​

Does the with block close the connection?​

No. The documentation's note: "The context manager neither implicitly opens a new transaction on entry nor closes the connection."

Do I still need commit()?​

Not for changes made inside a with connection: block: the block commits them when it ends without an error.

Conclusion​

The first with connection: block committed Ana. The second failed on its duplicate insert, and the rollback took Ben with it, so the table was exactly as before the block.

Additional Resources​