Values belong in parameters.
Insert records with bound values instead of building SQL from input strings.
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.
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"])6
03 Under the hood
- 1
Each tuple supplies five values for the five named columns. Explicit column lists make inserts less fragile when a schema evolves.
- 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
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
Insert a task whose name contains an apostrophe using a bound value.
Reveal one possible solution +
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
Where should input values go?
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 ↗.