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

Values belong in parameters.

Insert records with bound values instead of building SQL from input strings.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Parameterized queries separate SQL structure from data. Connector/Python uses %s placeholders for values regardless of whether the Python value is a string or a number. Pass the values as a separate tuple. executemany applies a parameterized operation to multiple records. Commit intentionally when those writes should persist within the session’s transactional data.

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

with mysql_lab() as (connection, cursor):
    records = [(5, 2, "Document", 10, False), (6, 2, "Ship", 5, False)]
    cursor.executemany("INSERT INTO lab_tasks (id, project_id, name, minutes, done) VALUES (%s, %s, %s, %s, %s)", records)
    connection.commit()
    cursor.execute("SELECT COUNT(*) AS total FROM lab_tasks")
    print(cursor.fetchone()["total"])
↳ EXPECTED OUTPUT
6

03 Under the hood

  1. 1

    Each tuple supplies five values for the five named columns. Explicit column lists make inserts less fragile when a schema evolves.

  2. 2

    A single value still needs a one-item tuple such as (name,). Do not wrap the %s placeholder in quotes; the connector handles value encoding.

  3. 3

    Bound values cannot substitute identifiers such as table or column names. When an identifier genuinely varies, map an allowed application choice to a fixed, reviewed identifier.

04 Your turn, builder

A SMALL MISSION

Insert a task whose name contains an apostrophe using a bound value.

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

with mysql_lab() as (connection, cursor):
    name = "Review Navan's notes"
    cursor.execute("INSERT INTO lab_tasks (id, project_id, name, minutes, done) VALUES (%s, %s, %s, %s, %s)", (5, 1, name, 10, False))
    connection.commit()
    cursor.execute("SELECT name FROM lab_tasks WHERE id = %s", (5,))
    print(cursor.fetchone()["name"])

05 Check your signal

QUICK SIGNAL CHECK

Where should input values go?

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.