Sub topic 10
Diagnosing common errors and warnings
This chapter assumes you can connect with sqlite3 or a SQLAlchemy engine, call read_sql_query with params, and read a traceback. Most failures in pandas.read_sql_* come from a few causes: the wrong connection type, the wrong placeholder style, a closed connection, or surprising dtypes. Each one has a recognizable message.
A triage flow
Start with the exception type and the first line of its message. Pandas often wraps the driver's error in pandas.errors.DatabaseError, so read the text after "Execution failed on sql" to find the real cause.
Warning: unsupported connection
Pandas officially supports SQLAlchemy connectables, a database URI string, and sqlite3 connections. If you pass another DBAPI object, such as a psycopg2 or pymysql connection, you get a UserWarning saying pandas only supports those types and that other DBAPI2 objects are not tested. The query usually still runs, but behavior is not guaranteed. The fix is to wrap the database in a SQLAlchemy engine:
from sqlalchemy import create_engine
engine = create_engine("sqlite:///shop.db")If you pass a URI string and SQLAlchemy is not installed, you get an ImportError instead. Install SQLAlchemy.
Errors from the placeholder style
Every driver has its own placeholder style. Using the wrong one produces a syntax error or a binding error.
| Connection | Placeholder style | Example |
|---|---|---|
| `sqlite3` | qmark, or named | `WHERE total >= ?` or `:min_total` |
| `psycopg2`, `pymysql` | format or pyformat | `%s` or `%(name)s` |
| SQLAlchemy with `text()` | named | `:name` |
The script below reproduces three common mistakes against an in-memory database. Each call is wrapped so you can see the exception type and message.
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total REAL);
INSERT INTO orders VALUES (1, 'Ada', 120.5), (2, 'Grace', 80.0), (3, 'Ada', NULL);
""")
def attempt(label, func):
try:
func()
except Exception as exc:
print(f"{label}: {type(exc).__name__}: {str(exc)[:90]}")
# 1. %s is not a sqlite3 placeholder
attempt("wrong style", lambda: pd.read_sql_query(
"SELECT * FROM orders WHERE customer = %s", conn, params=("Ada",)))
# 2. ("Ada") is just the string "Ada", not a tuple, so it counts as 3 values
attempt("not a tuple", lambda: pd.read_sql_query(
"SELECT * FROM orders WHERE customer = ?", conn, params=("Ada")))
# 3. read_sql_table needs SQLAlchemy
attempt("table on sqlite3", lambda: pd.read_sql_table("orders", conn))The three cases fail for these reasons:
- Wrong style: the first query fails with a syntax error near
%. Switch to?forsqlite3. - Not a tuple: the second fails with "Incorrect number of bindings". A one-element tuple needs a trailing comma,
("Ada",). A bare string is treated as a sequence of characters. - Table on
sqlite3: the third fails becauseread_sql_tableonly works with a SQLAlchemy connectable. Pass an engine, or useread_sql_query("SELECT * FROM orders", conn).
Do not "fix" a binding error by formatting values into the SQL string with an f-string. That opens the door to SQL injection. Correct the params shape instead.
Missing tables and silent new files
sqlite3.connect("shop.db") creates an empty file if the path does not exist. A wrong relative path therefore does not fail at connection time. It fails later with no such table: orders. When you see that message, check the working directory with os.getcwd() and check that the file is not zero bytes.
Reading after the connection is closed
With chunksize, read_sql_query returns an iterator, and rows are fetched as you loop. If you leave a with block or call conn.close() before consuming the iterator, the fetch fails. For sqlite3 the error is Cannot operate on a closed database. Keep the connection open for the whole loop:
total = 0.0
for chunk in pd.read_sql_query("SELECT * FROM orders", conn, chunksize=2):
total += chunk["total"].sum()
print(total)Without chunksize, the data is fully loaded before the call returns. Closing the connection afterward is safe.
No error, but the wrong dtypes
Some problems raise nothing. Check df.dtypes after loading.
- NULL in an integer column: pandas has no NaN for plain
int64, so the column becomesfloat64. Usedf["col"].astype("Int64")for a nullable integer type. - Dates as
object: SQLite stores dates as text, so they load as strings. Passparse_dates=["created_at"]. If parsing fails or returns strings, the text may not be in a consistent format. Useparse_dates={"created_at": {"format": "%Y-%m-%d"}}to be explicit. - Numbers stored as text: convert with
pd.to_numeric(df["col"], errors="coerce"). Rows that cannot convert become NaN, which you can then find.
Version mismatches
Older pandas (before 2.0) does not work with SQLAlchemy 2.0. The usual symptom is an AttributeError such as 'OptionEngine' object has no attribute 'execute'. Upgrade pandas, or pin SQLAlchemy below 2.0. Check both with pd.__version__ and sqlalchemy.__version__.
Exercise
Your teammate passes a psycopg2 connection to pd.readsqlquery with the query "SELECT * FROM users WHERE id = ?" and params=(7,). Name the two problems and the fix for each.
Show answer
First, pandas emits a UserWarning because a raw psycopg2 connection is not a supported type. Wrap the database in a SQLAlchemy engine, for example create_engine("postgresql+psycopg2://..."). Second, "?" is the sqlite3 qmark style, and psycopg2 expects "%s". Once you switch to an engine, write the query with text() and a named parameter such as "WHERE id = :id" and pass params={"id": 7}.
Exercise
A loop over pd.readsqlquery(..., conn, chunksize=1000) fails on the first iteration with "Cannot operate on a closed database". The conn.close() call sits just above the loop. What is wrong?
Show answer
With chunksize, the query returns an iterator and rows are fetched during the loop. Closing the connection before the loop leaves nothing to fetch from. Move conn.close() to after the loop, or put the loop inside the with block that owns the connection.