Sub topic 4
Passing values safely with params
This chapter assumes you can run a basic pd.read_sql_query call, you know what a connection object is, and you know simple SQL WHERE clauses. The examples use the orders table and the conn sqlite3 connection from the earlier chapters.
Why not build the SQL string yourself
A common first attempt is to paste a value into the query with an f-string:
name = "Ada"
query = f"SELECT * FROM orders WHERE customer = '{name}'"This works for friendly input and breaks for everything else. If name comes from a user, a form, or a file, it can contain quote characters or SQL fragments. A value such as x' OR '1'='1 changes the meaning of the query. This attack is called SQL injection. Even without an attacker, a customer named O'Brien produces a syntax error.
The fix is to keep the SQL text and the values separate. You write the query with placeholders, and the database driver binds the values for you. The driver sends them as data, never as SQL code, so no quoting or escaping is needed on your side.
Using params with sqlite3
read_sql_query accepts a params argument. With a plain sqlite3 connection, use the ? placeholder (the qmark style) and pass the values as a tuple or list, in the same order as the placeholders.
df = pd.read_sql_query(
"SELECT id, customer, total FROM orders WHERE total >= ? AND customer = ?",
conn,
params=(100, "Ada"),
)
print(df)The first ? receives 100 and the second receives "Ada". The driver also keeps the types: 100 is sent as a number, so no quotes are added around it.
A sqlite3 connection also accepts named placeholders written as :name, with a dictionary:
df = pd.read_sql_query(
"SELECT * FROM orders WHERE customer = :name",
conn,
params={"name": "Ada"},
)Using params with SQLAlchemy
With a SQLAlchemy connection, wrap the query in text() and use named placeholders written as :name. Pass the values as a dictionary.
from sqlalchemy import create_engine, text
import pandas as pd
engine = create_engine("sqlite:///shop.db")
with engine.connect() as connection:
ada = pd.read_sql_query(
text("SELECT * FROM orders WHERE customer = :name"),
connection,
params={"name": "Ada"},
)
print(ada)text() marks the string as SQL that SQLAlchemy should parse for named placeholders. Without it, a plain string goes straight to the driver, and the driver's own placeholder style applies.
Placeholder styles depend on the driver
The placeholder syntax is defined by the database driver, not by pandas. Pandas passes params through unchanged.
| Driver | Placeholder style | Example | `params` type |
|---|---|---|---|
| `sqlite3` | qmark or named | `WHERE id = ?` or `:id` | tuple or dict |
| `psycopg2` (PostgreSQL) | format or pyformat | `WHERE id = %s` or `%(id)s` | tuple or dict |
| `pymysql` (MySQL) | format or pyformat | `WHERE id = %s` or `%(id)s` | tuple or dict |
| SQLAlchemy `text()` | named | `WHERE id = :id` | dict |
If you copy a query written for one driver into another, expect a parameter style error. The troubleshooting chapter covers those messages.
What params cannot do
Placeholders stand in for values only. You cannot use them for table names, column names, or SQL keywords.
# This does not work: the driver treats the table name as a value.
pd.read_sql_query("SELECT * FROM ? WHERE id = 1", conn, params=("orders",))If a table or column name must be dynamic, check it against a fixed list of allowed names in Python before putting it into the string:
allowed_columns = {"id", "customer", "total", "created_at"}
sort_column = "total"
if sort_column not in allowed_columns:
raise ValueError(f"Unsupported column: {sort_column}")
df = pd.read_sql_query(
f"SELECT * FROM orders ORDER BY {sort_column}",
conn,
)The f-string here is safe only because sort_column was checked against a list that you control.
Lists of values with IN
A single placeholder holds a single value, so WHERE customer IN (?) with a list does not work. Build one placeholder per item and pass the items as the parameters:
customers = ["Ada", "Grace"]
placeholders = ", ".join("?" * len(customers))
df = pd.read_sql_query(
f"SELECT * FROM orders WHERE customer IN ({placeholders})",
conn,
params=customers,
)
print(df)Only the placeholder string is formatted into the SQL. The values still travel through params.
Common mistakes
- Passing a bare value instead of a sequence.
params=("Ada")is just the string"Ada", because parentheses alone do not make a tuple. Writeparams=("Ada",)with a trailing comma. - Mixing styles in one query, such as
?together with:name. - Adding quotes around the placeholder, as in
'?'. The driver then sees a string literal and finds no parameter to bind. - Giving the wrong number of values for the number of placeholders.
Exercise
Exercise
A colleague writes pd.read_sql_query("SELECT * FROM orders WHERE customer = ?", conn, params=("Ada")) and gets an error about the number of bindings. What is wrong, and how do you fix it?
Show answer
("Ada") is a plain string, not a tuple, so sqlite3 treats it as three separate values (one per character) for a single placeholder. Add a trailing comma, params=("Ada",), or use a list, params=["Ada"].
Exercise
Write a call that returns orders with a total below 150 for customers "Ada" or "Grace", using the sqlite3 connection conn and no string formatting of values.
Show answer
Use one placeholder per customer and pass every value in params: pd.readsqlquery("SELECT * FROM orders WHERE total < ? AND customer IN (?, ?)", conn, params=(150, "Ada", "Grace"))