
Code
Transfer the Lantern Fuel
Fog Reach is running dry. Pip wants to move 3 barrels from Amber Isle. That's two changes: take from one depot, add to another.
UPDATE changes rows
cur = conn.execute(
"UPDATE depots SET barrels = barrels - ? "
"WHERE island = ?",
(3, "Amber Isle"),
)
print(cur.rowcount) # how many rows changed
Always include WHERE, or every row changes! If rowcount is
0, no row matched: maybe the island name is wrong.
Transactions: all or nothing
What if the first UPDATE works and the second fails? Barrels would
vanish. A transaction groups changes so they all happen, or none
do. In sqlite3, use the connection in a with block:
with conn:
conn.execute(...) # change 1
conn.execute(...) # change 2
- If the block finishes, the changes are committed (saved).
- If an exception escapes the block, they are rolled back (undone), and the exception carries on.
So you can raise an error on purpose to cancel everything.
(with conn: doesn't close the connection. It just handles the
transaction.)
Assignment
Table: depots(island TEXT PRIMARY KEY, barrels INTEGER).
refuel(conn, island, barrels)addsbarrelsto that island, insidewith conn:. If no row changed, raiseKeyError(island).transfer(conn, giver, taker, barrels)takesbarrelsfromgiverand adds them totaker, inside onewith conn:block. If either UPDATE changes 0 rows, raiseKeyError, so the whole transfer is rolled back.
Table: depots(island TEXT PRIMARY KEY, barrels INTEGER).
refuel(conn, island, barrels)addsbarrelsto that island, insidewith conn:. If no row changed, raiseKeyError(island).transfer(conn, giver, taker, barrels)takesbarrelsfromgiverand adds them totaker, inside onewith conn:block. If either UPDATE changes 0 rows, raiseKeyError, so the whole transfer is rolled back.
main.py Python sleeping
Press Run to try your code, then Check to test it.