← SQL Deep Dive
11 / 25
Lesson 11 — Transactions
Transactions with "with db:"
A transaction makes several changes atomic: all succeed or none do. Python's sqlite3 gives a clean way: with db: commits when the block ends normally and rolls back (undoes) everything if an error escapes the block.
with db:
db.execute("INSERT ...")
db.execute("INSERT ...") # if this fails, the first is undone too
Why it matters: an order without its order lines, or stock reduced without a sale, is corrupt data. Transactions prevent half-finished work.
Want it another way?
Task
Wrap the two INSERTs of place_order in a with db: block. The broken order (qty 0) must leave no trace. Expected: 1 order, 1 line.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.