How to Commit or Roll Back SQLite Changes in Python with a with Block
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
with connection:
connection.execute("<first change>")
connection.execute("<second change>")
| Part | What it means |
|---|---|
with connection: | Starts the block. The changes inside it form one transaction |
| End of the block, no error | sqlite3 commits the changes |
| An exception inside the block | sqlite3 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:
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 first block inserts Ana and ends normally.
- The second block inserts Ben, then tries to insert Ana again, which breaks the primary key.
- The
tryandexceptsit outside thewithblock, so the error leaves the block first.
Step 2: Run It
uv run python with_connection.py
After the first block: [('Ana', 100)]
Rolled back: UNIQUE constraint failed: members.name
After the second block: [('Ana', 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
| Mistake | What happens | Do this instead |
|---|---|---|
Catching the error inside the with block | The block ends without an exception, so it commits: Ben is saved even though Ana's insert failed | Let the error leave the block, and catch it outside |
Expecting with connection: to close the connection | It stays open: the script above queries it after both blocks | Call 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
| Symptom | Likely cause | Fix |
|---|---|---|
| Part of a failed block's changes stayed in the database | The exception was caught inside the block | Move 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
- How to use the connection context manager — commit, rollback and what the block doesn't do.
- Connection.commit — committing by hand.
