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

All of it, or none of it.

Group related row changes and recover deliberately when a rule fails.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

A transaction groups operations into a unit that can be committed or rolled back. With InnoDB tables, this lets an application avoid leaving half of a multi-step change behind. Isolation controls how concurrent work becomes visible; it does not mean every business rule is automatically safe from races. Keep transactions short, check expectations, and choose a concurrency strategy for shared state.

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_transactions.py
from lab_support import mysql_lab

with mysql_lab() as (connection, cursor):
    try:
        cursor.execute("UPDATE lab_tasks SET minutes = minutes - %s WHERE id = %s", (10, 2))
        cursor.execute("UPDATE lab_tasks SET minutes = minutes + %s WHERE id = %s", (10, 3))
        raise ValueError("Cancel this practice transfer")
    except ValueError:
        connection.rollback()
    cursor.execute("SELECT name, minutes FROM lab_tasks WHERE id IN (%s, %s) ORDER BY id", (2, 3))
    for row in cursor.fetchall():
        print(row["name"], row["minutes"])
↳ EXPECTED OUTPUT
Build 40
Test 20

03 Under the hood

  1. 1

    The helper commits its starting fixture before yielding, so rollback returns to that stable baseline.

  2. 2

    The deliberate failure occurs after both updates. rollback discards those uncommitted row changes rather than leaving a partial transfer.

  3. 3

    For concurrent transfers, use suitable locking or conditional updates and check affected rows. Deadlocks can occur even in correct designs; retry a complete transaction only under a deliberate policy and with idempotency in mind.

04 Your turn, builder

A SMALL MISSION

Perform the same duration transfer successfully, committing both changes.

Reveal one possible solution +
one_possible_solution.py
from lab_support import mysql_lab

with mysql_lab() as (connection, cursor):
    try:
        cursor.execute("UPDATE lab_tasks SET minutes = minutes - %s WHERE id = %s", (10, 2))
        cursor.execute("UPDATE lab_tasks SET minutes = minutes + %s WHERE id = %s", (10, 3))
        connection.commit()
    except Exception:
        connection.rollback()
        raise
    cursor.execute("SELECT minutes FROM lab_tasks WHERE id IN (%s, %s) ORDER BY id", (2, 3))
    print([row["minutes"] for row in cursor.fetchall()])

05 Check your signal

QUICK SIGNAL CHECK

What does rollback discard here?

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.