Change exactly what you mean.
Preview a predicate, target specific rows, and check the effect of a mutation.
01 The idea
UPDATE and DELETE operate on every row matching their WHERE predicate. Without a WHERE clause, they can affect the entire table. A safe workflow first checks that the predicate describes the intended records, performs a parameterized mutation, then inspects affected rows and commits or rolls back deliberately. Transactions do not replace a correct predicate.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from lab_support import mysql_lab
with mysql_lab() as (connection, cursor):
cursor.execute("UPDATE lab_tasks SET done = %s WHERE id = %s", (True, 2))
print("updated:", cursor.rowcount)
cursor.execute("DELETE FROM lab_tasks WHERE id = %s AND done = %s", (1, True))
print("deleted:", cursor.rowcount)
connection.commit()
cursor.execute("SELECT COUNT(*) AS total FROM lab_tasks")
print("remaining:", cursor.fetchone()["total"])updated: 1 deleted: 1 remaining: 3
03 Under the hood
- 1
The update targets a primary key, so it cannot unintentionally match several task identities. The fixture’s Build row actually changes from false to true.
- 2
The delete includes both id and expected state. Real applications can include a version column in the predicate for optimistic concurrency.
- 3
Affected-row semantics can depend on operation and connector flags. In MySQL, an UPDATE that assigns the existing value may report zero changed rows even though the predicate matched.
04 Your turn, builder
Increase Test’s duration by five minutes and read the new value back.
Reveal one possible solution +
from lab_support import mysql_lab
with mysql_lab() as (connection, cursor):
cursor.execute("UPDATE lab_tasks SET minutes = minutes + %s WHERE id = %s", (5, 3))
connection.commit()
cursor.execute("SELECT minutes FROM lab_tasks WHERE id = %s", (3,))
print(cursor.fetchone()["minutes"])05 Check your signal
Which clause limits rows affected by DELETE?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.