Sub topic 2
Passing values safely with `params`
Assume basic Python, pandas, and SQL, including SELECT, WHERE, and GROUP BY. The examples use SQLite and its ? parameter style.
Passing values safely with `params`
Do not insert Python values into SQL with string formatting. A parameterized query keeps SQL code separate from data. The database driver binds each value and handles quoting safely.
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.executescript("""
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');
""")
minimum_total = 100
customer = "Ada"
df = pd.read_sql_query(
"""
SELECT id, customer, total
FROM orders
WHERE total >= ? AND customer = ?
""",
conn,
params=(minimum_total, customer),
)
print(df)The placeholder syntax belongs to the database driver. SQLite uses ?; other drivers may use named placeholders such as :name. Do not mix styles.
Controlling the index, dates, and dtypes
SQL results normally become a DataFrame with a default integer index. Use index_col for a meaningful index, parse_dates for date columns, and dtype when pandas should enforce a specific type.
df = pd.read_sql_query(
"SELECT id, customer, total, created_at FROM orders",
conn,
index_col="id",
parse_dates=["created_at"],
dtype={"customer": "string"},
)
print(df.dtypes)NULL values become pandas missing values. A numeric column containing missing values may use a nullable pandas type, such as Int64, rather than the ordinary int64.
Deciding what to do in SQL and what in pandas
Filter and aggregate in SQL when the database can reduce the number of rows transferred. Use pandas for analysis that depends on DataFrame operations or follows after loading a manageable result.
Exercise
Why is params=(100, "Ada") preferable to formatting those values into the SQL string?
Show answer
The driver binds the values separately, which avoids quoting mistakes and reduces SQL injection risk.