Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python meets MySQL
EXPERIMENT 83 / 101

Change exactly what you mean.

Preview a predicate, target specific rows, and check the effect of a mutation.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

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.

mysql_update_delete.py
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"])
↳ EXPECTED OUTPUT
updated: 1
deleted: 1
remaining: 3

03 Under the hood

  1. 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. 2

    The delete includes both id and expected state. Real applications can include a version column in the predicate for optimistic concurrency.

  3. 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

A SMALL MISSION

Increase Test’s duration by five minutes and read the new value back.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

Which clause limits rows affected by DELETE?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.