Sub topic 4
Passing values safely with params
This chapter covers how to put Python values into a SQL query when you load data with pandas.read_sql_query. It assumes you can run a query into a DataFrame (previous chapter), know basic SQL WHERE clauses, and understand Python tuples, lists and dicts.
By the end you should be able to:
- explain why string formatting is unsafe and what binding does instead
- pick the right placeholder style for your driver
- handle lists,
LIKEpatterns, dates andNULL - recognize the cases where parameters cannot help
- diagnose the usual parameter errors
Why string formatting is the wrong tool
The quickest way to put a value into a query is an f-string. It works until the value comes from somewhere you do not control, such as a web form, a CSV file or a command-line argument.
The examples use the shop.db file from earlier chapters. This block recreates it if you need it.
import sqlite3
conn = sqlite3.connect("shop.db")
conn.executescript("""
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total REAL, created_at TEXT);
INSERT INTO orders VALUES
(1, 'Ada', 120.5, '2024-01-05'),
(2, 'Grace', 80.0, '2024-01-09'),
(3, 'Ada', 200.0, '2024-02-01');
""")
conn.commit()
conn.close()Now build a query by pasting a value into the text:
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
customer = "Ada' OR '1'='1"
query = f"SELECT id, customer, total FROM orders WHERE customer = '{customer}'"
print(query)
df = pd.read_sql_query(query, conn)
print(df)The printed SQL is ... WHERE customer = 'Ada' OR '1'='1'. The quote inside the value closed the string literal, and the rest of the value became SQL. The condition '1'='1' is always true, so the query returns all three rows, not just Ada's. This is SQL injection. Here it leaks rows. With other drivers and other statements it can modify or delete data.
Even without an attacker, string formatting breaks on honest input. A customer named O'Brien produces invalid SQL because of the apostrophe.
How binding works
The fix is to send the query text and the values separately. You write placeholders in the SQL, and the database driver binds the values to them. The database parses the SQL first. Values arrive afterwards as data, so they can never change the structure of the statement.
In read_sql_query you do this with the params argument. Pandas does not build the final string. It passes the SQL and params to the driver.
Repeat the earlier query with the malicious value, this time bound:
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
customer = "Ada' OR '1'='1"
df = pd.read_sql_query(
"SELECT id, customer, total FROM orders WHERE customer = ?",
conn,
params=(customer,),
)
print(df)The result is an empty DataFrame that still has the columns id, customer and total. No customer is literally named Ada' OR '1'='1, and that is the correct answer.
Placeholder styles depend on the driver
Placeholders are not the same everywhere. Each Python database driver declares a paramstyle, and you must write placeholders in that style. Pandas does not translate between them.
| Driver or layer | Style | Positional placeholder | Named placeholder |
|---|---|---|---|
| `sqlite3` | qmark and named | `?` | `:name` |
| `psycopg2`, `psycopg` (v3) | format and pyformat | `%s` | `%(name)s` |
| `pymysql`, `mysqlclient` | format and pyformat | `%s` | `%(name)s` |
| SQLAlchemy `text()` | named | not available | `:name` |
You can check what a driver expects:
import sqlite3
print(sqlite3.paramstyle)For sqlite3 this prints qmark. The module accepts both ? and :name regardless of that attribute.
The most common error is writing ? for a PostgreSQL connection, or %s for SQLite, and getting a syntax error from the driver. If the error mentions the placeholder character, check the style first.
Positional and named parameters
params accepts a sequence (tuple or list) or a mapping (dict). The container must match the placeholder kind.
Positional placeholders pair with a sequence, matched by order:
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
df = pd.read_sql_query(
"SELECT id, customer, total FROM orders WHERE total >= ? AND customer = ?",
conn,
params=(100, "Ada"),
)
print(df)Named placeholders pair with a dict, matched by key:
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
df = pd.read_sql_query(
"SELECT id, customer, total FROM orders "
"WHERE total >= :min_total AND customer = :name",
conn,
params={"min_total": 100, "name": "Ada"},
)
print(df)Both return orders 1 and 3. Named style costs more typing, but it reads better once a query has more than two or three values. It also lets you use one value several times without repeating it in the tuple.
The one-element tuple trap
A tuple is made by the comma, not the parentheses. ("Ada") is just the string "Ada". SQLite then treats the string as a sequence of three characters and complains about too many bindings.
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
sql = "SELECT id, customer, total FROM orders WHERE customer = ?"
try:
pd.read_sql_query(sql, conn, params=("Ada"))
except Exception as exc:
print(type(exc).__name__)
print(exc)
print(pd.read_sql_query(sql, conn, params=("Ada",)))The first call raises pandas.errors.DatabaseError. Its message wraps the driver's complaint, along the lines of "Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied." The second call, with the trailing comma, works. A list ["Ada"] avoids the problem and is a fine alternative.
Lists of values and `IN`
A placeholder stands for one value. You cannot bind a whole list to IN (?). Instead, generate one placeholder per element and pass the list as the parameters:
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
names = ["Ada", "Grace"]
if not names:
raise ValueError("names must not be empty")
placeholders = ", ".join("?" for _ in names)
query = f"SELECT id, customer, total FROM orders WHERE customer IN ({placeholders})"
print(query)
df = pd.read_sql_query(query, conn, params=names)
print(df)The f-string is safe here because it inserts only the text ?, once per element, and the length is the only thing that varies. The names themselves still travel through params.
Handle the empty list yourself. IN () is a syntax error in most databases, and a query with no names usually means "return nothing", which you can decide in Python without querying.
Databases also limit how many parameters one statement can take. Older SQLite builds allow 999. If your list can be in the thousands, load it into a temporary table or process it in batches.
Patterns, dates and NULL
LIKE patterns
Put the wildcard in the value, not in the SQL:
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
prefix = "A"
df = pd.read_sql_query(
"SELECT id, customer FROM orders WHERE customer LIKE ?",
conn,
params=(prefix + "%",),
)
print(df)Writing LIKE '?%' does not work, because a placeholder inside a quoted literal is just text. If the user's input may contain % or _, escape them yourself and add an ESCAPE clause. Binding stops them from changing the SQL structure, but LIKE still treats them as wildcards.
Dates
SQLite stores dates as text, so pass ISO 8601 strings, which sort correctly. Python 3.12 deprecated the default sqlite3 adapters for date and datetime objects, so call .isoformat() yourself:
import sqlite3
from datetime import date
import pandas as pd
conn = sqlite3.connect("shop.db")
start = date(2024, 1, 1)
end = date(2024, 1, 31)
df = pd.read_sql_query(
"SELECT id, customer, created_at FROM orders WHERE created_at BETWEEN ? AND ?",
conn,
params=(start.isoformat(), end.isoformat()),
parse_dates=["created_at"],
)
print(df)
print(df.dtypes)This returns orders 1 and 2, and created_at arrives as datetime64[ns] because of parse_dates. Server databases with real date types, such as PostgreSQL, accept date and datetime objects directly.
None and NULL
Python None binds as SQL NULL. In SQL, column = NULL is never true, so this query returns no rows even when some customer values are NULL:
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
df = pd.read_sql_query(
"SELECT id FROM orders WHERE customer = ?", conn, params=(None,)
)
print(len(df))It prints 0. If a value may be missing, write the comparison for it. In SQLite, customer IS ? treats NULL as an ordinary value. Other databases use IS NOT DISTINCT FROM. Often the clearer approach is to choose between IS NULL and = ? in Python.
NumPy and pandas scalars
Values taken from a DataFrame are often numpy.int64 or numpy.float64. Drivers such as sqlite3 typically reject these types with an error about an unsupported type. Convert to native Python values first:
import sqlite3
import numpy as np
import pandas as pd
conn = sqlite3.connect("shop.db")
threshold = np.int64(100)
df = pd.read_sql_query(
"SELECT id, customer, total FROM orders WHERE total >= ?",
conn,
params=(int(threshold),),
)
print(df)For a value from a Series, .item() does the same conversion.
What parameters cannot do
Binding applies only to values. The database must know the structure of a statement before it receives any value, so these cannot be parameters:
- table names and column names
- SQL keywords such as
ASCandDESC - operators and function names
If a column or table name comes from outside, check it against a fixed allowlist and only then put it into the text:
import sqlite3
import pandas as pd
ALLOWED_SORT_COLUMNS = {"id", "customer", "total", "created_at"}
def orders_sorted(conn, column, min_total):
if column not in ALLOWED_SORT_COLUMNS:
raise ValueError(f"cannot sort by {column!r}")
query = (
"SELECT id, customer, total FROM orders "
f"WHERE total >= ? ORDER BY {column}"
)
return pd.read_sql_query(query, conn, params=(min_total,))
conn = sqlite3.connect("shop.db")
print(orders_sorted(conn, "total", 50))Checking against a set you wrote is safe. "Sanitizing" a name by stripping characters is not. Keep the value part bound and only the identifier checked.
Parameters with SQLAlchemy
When you pass a SQLAlchemy connection, how you write the query matters. If you pass a plain string, pandas hands it to the underlying driver, so you must use the driver's own placeholder style (%s for psycopg2). If you wrap the string in sqlalchemy.text(), you get portable named placeholders written as :name, and SQLAlchemy translates them for whatever database is behind the engine.
text() also solves the list problem. Mark the parameter as expanding and SQLAlchemy writes the right number of placeholders at execution time:
import pandas as pd
from sqlalchemy import bindparam, create_engine, text
engine = create_engine("sqlite:///shop.db")
query = text(
"SELECT id, customer, total FROM orders "
"WHERE customer IN :names AND total >= :min_total"
).bindparams(bindparam("names", expanding=True))
with engine.connect() as connection:
df = pd.read_sql_query(
query,
connection,
params={"names": ["Ada", "Grace"], "min_total": 100},
)
print(df)This returns orders 1 and 3. The empty-list problem also goes away in recent SQLAlchemy versions, which render an empty IN that matches nothing. Test this on your database and version before relying on it.
Common parameter errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Error says "Incorrect number of bindings supplied" | Count mismatch, or a bare string like `("Ada")` passed as params | Count the placeholders, and write `("Ada",)` or `["Ada"]` |
| Error says "You did not supply a value for binding parameter" | A named placeholder has no matching dict key | Check spelling, since keys are case-sensitive |
| Syntax error near `?`, `%` or `:` | Placeholder style does not match the driver | Check `paramstyle`, or use `text()` with SQLAlchemy |
| Error about an unsupported type when binding | NumPy scalar, `Decimal` or custom object passed | Convert to `int`, `float` or `str` |
| Query returns no rows for `None` | `= NULL` is never true | Use `IS NULL` or `IS ?` |
| psycopg2 error mentioning a stray `%` | Literal `%` in the SQL while params are given | Write `%%` for a literal percent sign |
Summary
- Pass values through
params. Never format them into the SQL text. - Match the placeholder style to the driver:
?or:namefor sqlite3,%sor%(name)sfor psycopg and MySQL drivers,:nameinsidetext()for SQLAlchemy. - Use a tuple or list with positional placeholders, and a dict with named ones. Watch for the one-element tuple.
- Build
INlists by generating placeholders, or use anexpandingbind parameter in SQLAlchemy. - Convert dates and NumPy scalars to native types, and handle
Noneexplicitly. - Identifiers and keywords cannot be bound. Check them against an allowlist.
Exercise
A colleague writes pd.read_sql_query("SELECT * FROM orders WHERE customer = ?", conn, params=("Grace")) against SQLite and gets a DatabaseError about bindings. What is wrong, and what are two ways to fix it?
Show answer
("Grace") is a plain string, not a tuple, so sqlite3 sees five separate characters as five values for one placeholder. Fix it by adding the trailing comma, params=("Grace",), or by passing a list, params=["Grace"].
Exercise
You need all orders for customers in a Python list names with total at or above a threshold, using sqlite3. Describe how to build the query and the params, and say what to do when names is empty.
Show answer
Build one placeholder per name with ", ".join("?" for _ in names) and insert it into IN (...) in the SQL text. Then pass params=[*names, threshold], where the threshold matches a final AND total >= ? placeholder. If names is empty, skip the query and return an empty DataFrame, because IN () is a syntax error in most databases.
Exercise
A function lets the caller choose the table to read from, and you plan to pass the table name through params. Why will this fail, and what is a safe approach?
Show answer
Placeholders can only stand for values, not identifiers, so the database rejects or misreads a bound table name. Check the requested name against a hard-coded set of allowed tables and put the validated name into the SQL text. Keep any filter values in params.