Pass the value separately with a placeholder
Put a placeholder, such as ? or %s, where the value belongs in the SQL text. Then pass the value as a second argument to the cursor’s execute() method. The driver fills in the placeholder and handles the quoting. The Python standard library’s sqlite3 documentation recommends this approach, and it keeps the value out of the SQL text, so quotes or unusual characters in the value cannot change the query.
Here is the pattern with sqlite3, which ships with Python:
import sqlite3
conn = sqlite3.connect("shop.db")
cur = conn.cursor()
customer_name = "Ava"
cur.execute("SELECT id, total FROM orders WHERE customer = ?", (customer_name,))
rows = cur.fetchall()
The second argument is a tuple. The comma after customer_name makes it one. Without the comma, (customer_name) is just the value in parentheses, not a tuple.
Placeholder syntax depends on the driver
Each database driver uses its own placeholder syntax. A ? that works with sqlite3 will not work with psycopg2, and a %s that works with PyMySQL will not work with sqlite3.
| Driver | Database | Placeholder |
|---|---|---|
sqlite3 (standard library) |
SQLite | ? or :name |
psycopg2 |
PostgreSQL | %s or %(name)s |
PyMySQL |
MySQL and MariaDB | %s |
pyodbc |
SQL Server and other ODBC data sources | ? |
SQLAlchemy text() |
Any database SQLAlchemy supports | :name |
Check your driver’s documentation for the style it expects.
Named placeholders for several values
When a query uses more than one value, named placeholders make the code easier to read. With sqlite3, write :name and pass a dictionary:
cur.execute(
"SELECT id, total FROM orders WHERE customer = :name AND total > :min_total",
{"name": customer_name, "min_total": 50},
)
With psycopg2, use %(name)s with a dictionary:
cur.execute(
"SELECT id, total FROM orders WHERE customer = %(name)s AND total > %(min_total)s",
{"name": customer_name, "min_total": 50},
)
SQLAlchemy’s text() takes the same :name style, and the values go in a dictionary passed to execute().
Passing a list into an IN clause
Most drivers cannot take a Python list as a single parameter. Instead, make one placeholder for each item, join them with commas, and pass the items as the parameters:
ids = [3, 7, 12]
placeholders = ",".join(["?"] * len(ids))
sql = f"SELECT id, total FROM orders WHERE id IN ({placeholders})"
cur.execute(sql, ids)
The f-string here only inserts question marks. The values still go in as parameters.
An empty list needs its own handling. IN () is a syntax error in several databases, so return early or skip the query when the list is empty.
With PostgreSQL and psycopg2, a Python list can go into ANY. psycopg2 converts the list to a PostgreSQL array, so the query keeps one placeholder no matter how many items there are:
cur.execute("SELECT id, total FROM orders WHERE id = ANY(%s)", (ids,))
For lists of text values and the SQL Server options, see how to pass a list of strings in SQL query.
Placeholders only replace values
Placeholders stand in for values only. In most drivers, table names, column names and keywords such as ASC or DESC cannot be passed as parameters. If one of these comes from user input, check it against a list you control before you use it:
SORT_COLUMNS = {"date": "order_date", "total": "total"}
if sort_choice not in SORT_COLUMNS:
raise ValueError("unknown sort choice")
sql = f"SELECT id, total FROM orders ORDER BY {SORT_COLUMNS[sort_choice]}"
psycopg2 also provides psycopg2.sql.Identifier for quoting names. A check against a fixed list is the simpler option for most scripts.
Why building the string yourself is risky
Joining a value into the SQL text with an f-string, the % operator, + or .format() is a common source of SQL injection:
name = "Ava"
cur.execute(f"SELECT id, total FROM orders WHERE customer = '{name}'") # avoid
If name holds the text ' OR '1'='1, the WHERE clause becomes true for every row. Even without an attacker, a name such as O'Brien breaks the query with a syntax error. Passing the value as a parameter avoids both problems.
Common mistakes
A missing comma. (value) is not a tuple. Write (value,) for a single value.
None becomes NULL. When the Python value is None, the driver sends SQL NULL. A condition such as customer = ? never matches NULL, so use customer IS NULL in the SQL when you need to match missing values.
No commit. sqlite3, psycopg2 and PyMySQL do not keep changes from INSERT, UPDATE or DELETE statements until you call conn.commit():
cur.execute("UPDATE orders SET status = ? WHERE id = ?", ("shipped", 7))
conn.commit()
A literal percent sign. When you pass parameters to a driver that uses %s, a literal % in the SQL must be doubled. A LIKE pattern for names that start with “A” is written LIKE 'A%%' in that case.
A value of the wrong type. Send a value whose Python type matches the column. A number sent as text can compare differently from a number column, depending on the database. For the column types, see the different data types of sql and when to use each.
A short checklist
- Put a placeholder where each value goes, and pass the values in a tuple or a dictionary.
- Use the placeholder style your driver expects.
- Expand a list into one placeholder per item, and handle the empty list first.
- Check table and column names against a fixed list.
- Call
commit()after INSERT, UPDATE or DELETE statements.