Queries in Python

Running SQL from Python. The DB-API that database drivers share; connections, cursors and the fetch methods, and what rowcount does and does not report; parameter binding, and SQL injection demonstrated on a copy of the database, where one crafted drug name returns all 666 drugs and another returns the age of all 9,254 participants; identifiers that cannot be parameters; pandas.read_sql, the column types it produces and chunked reading; transactions, rollback and the connection context manager; and SQLAlchemy in brief. On the NHANES 2017-2018 database in SQLite.

Values belong in a query as parameters bound through placeholders, never formatted into the SQL text. On a copy of the NHANES 2017-2018 SQLite database, a drug search built by string formatting returns all 666 drugs for one crafted input and the age of all 9,254 participants for another; with a placeholder both return 0 rows. Doubling quotes stops those inputs but not 0 OR 1=1 in an unquoted number. Table and column names cannot be parameters and need an allow-list. pandas.read_sql types columns by the values that arrive, so a partly NULL integer column becomes float64. The connection's context manager undoes a failed two-step update only inside a transaction: by default all 282 codes survive; under autocommit=True 4 are converted and 278 remain (Python 3.13.5, SQLite 3.49.1).

A search box on a small web application looks up a drug by name. Its code builds the query by inserting the user's text into a string:

def find_drug(con, name):
    return con.execute(f"SELECT drug_id, name FROM drug WHERE name = '{name}'").fetchall()

Given ATORVASTATIN, it returns one row. Given x' OR '1'='1, it returns all 666 drugs in the database, because the text closes the quoted string and adds a condition that is always true. Given x' UNION SELECT seqn, age FROM person --, it returns 9,254 rows, the participant number and age of every person in the survey, through a search box meant for drug names. The same function written with a placeholder returns nothing for either input, because the text is then treated as a name to look for and never as SQL.

This article covers running SQL from Python: the common interface that database drivers implement, how to send queries and fetch their results, how to pass values into queries safely, how to read results into pandas, and how transactions keep a group of changes together. The examples use Python's built-in sqlite3 module and the NHANES database of the earlier articles in this topic, which starts with Relational Databases; every result quoted was produced by running the code.

The DB-API

Python's database drivers follow a common specification, the Python Database API Specification 2.0, published as PEP 249 (Lemburg, 1999). It defines a connection object, obtained from the driver's connect function, which represents a session with one database and controls transactions; and a cursor object, obtained from the connection, which executes statements and holds their results. Because the drivers for SQLite (sqlite3, in the standard library), PostgreSQL (psycopg), MySQL (mysql-connector-python) and others implement the same interface, code moves between them with few changes. The module reports which version it follows: sqlite3.apilevel is '2.0'.

What differs is how a connection is made. SQLite is a library that reads a file, so a connection needs only a path; sqlite3.connect(":memory:") creates a database that lives in memory and disappears when closed. A server database needs a host, a database name and credentials:

import os
import psycopg

con = psycopg.connect(host="db.example.org", dbname="survey", user="analyst",
                      password=os.environ["SURVEY_DB_PASSWORD"])

Passwords belong in the environment, a configuration file outside the code or a secrets manager, never in the source, where they end up in version control and in every copy of a notebook.

Cursors and fetching

import sqlite3

con = sqlite3.connect("nhanes.db")
cur = con.cursor()
cur.execute("SELECT seqn, sex, age FROM person WHERE age >= 18 ORDER BY seqn")

[d[0] for d in cur.description]   # ['seqn', 'sex', 'age']
cur.fetchone()                    # (93705, 'female', 66)
cur.fetchmany(2)                  # [(93706, 'male', 18), (93708, 'female', 66)]
rest = cur.fetchall()             # the remaining 5,853 rows
cur.fetchone()                    # None: nothing left

execute runs the statement; the rows are then fetched from the cursor, which keeps its place. fetchone returns the next row as a tuple, or None when there are no more; fetchmany(n) returns a list of up to n rows; fetchall returns all remaining rows. A cursor can also be iterated directly, for row in cur: ..., which fetches a row at a time and is the memory-efficient way to process a large result. cur.description gives the result's column names (with six other fields that sqlite3 leaves as None). sqlite3 connections have a shortcut, con.execute, that creates a cursor, executes and returns the cursor in one call.

Rows are tuples by default. Setting con.row_factory = sqlite3.Row makes them objects that can be indexed by column name, row["age"], as well as by position, which makes code that reads several columns less fragile.

One attribute does not do what its name suggests for queries. PEP 249 defines cursor.rowcount as the number of rows the last statement "produced (for DQL statements like SELECT) or affected (for DML statements like UPDATE or INSERT)", but allows -1 when the number "cannot be determined by the interface" (Lemburg, 1999). SQLite cannot know how many rows a query will return until they have all been produced, and the sqlite3 documentation states that rowcount "is -1 for other statements", meaning anything but INSERT, UPDATE, DELETE and REPLACE (Python Software Foundation, 2026). After the SELECT above it is -1. The number of rows returned is len(cur.fetchall()), or better a SELECT COUNT(*).

Parameters

Placeholders

Values that come from Python, such as a user's input, a loop variable or a threshold from a configuration file, are passed to a query as parameters: the SQL text contains a placeholder, and the values are supplied separately as the second argument of execute.

con.execute("SELECT COUNT(*) FROM person WHERE age >= ? AND sex = ?", (18, "female"))
con.execute("SELECT COUNT(*) FROM person WHERE age >= :lo AND sex = :sex",
            {"lo": 18, "sex": "female"})

Both return 3,016. sqlite3 accepts question marks, matched to a sequence by position (its paramstyle is 'qmark'), and named placeholders, matched to a dictionary (Python Software Foundation, 2026). PEP 249 allows five styles, and drivers differ: psycopg and the MySQL connector use %s and %(name)s. Those look like Python's string formatting but are not; the driver binds the values, and the query must still be passed as one string with the values separately. SQLite itself also accepts ?NNN, @name and $name (SQLite, n.d.-a).

Two details catch people out. A single parameter must still be in a sequence: (18) is just the integer 18 in parentheses, and sqlite3 rejects it with "parameters are of unsupported type"; (18,) is a tuple. And a list of values for IN needs one placeholder per value, built from the list's length:

names = ["ATORVASTATIN", "SIMVASTATIN", "ROSUVASTATIN"]
marks = ", ".join("?" for _ in names)                 # '?, ?, ?'
con.execute(f"SELECT COUNT(*) FROM drug WHERE name IN ({marks})", names)

The f-string here inserts only question marks, never data, so it is safe.

Why not format the string: SQL injection

Placeholders are not a matter of style. The function at the top of this article builds its query with an f-string, and its three inputs, run against an in-memory copy of the database, give:

Input Formatted into the string With a placeholder
ATORVASTATIN 1 row 1 row
x' OR '1'='1 666 rows (every drug) 0 rows
x' UNION SELECT seqn, age FROM person -- 9,254 rows (every person's age) 0 rows

This is SQL injection: input that changes the structure of the statement it is inserted into. The second input closes the string literal early and appends OR '1'='1', a condition true for every row. The third appends a second query whose rows are added to the result, and the -- comments out the stray quote that the original code supplies. A search box meant for drug names has disclosed data from a table the application never meant to show, which is why injection is treated as a security flaw and not merely a bug. The sqlite3 documentation gives the same warning with its own example and the instruction "Always use placeholders instead of string formatting to bind Python values to SQL statements, to avoid SQL injection attacks" (Python Software Foundation, 2026).

A placeholder prevents injection because the statement and the values travel separately: the database parses the SQL text, with a hole where the value goes, before it sees the value, so nothing in the value can become SQL. With a placeholder, x' OR '1'='1 is simply a drug name that does not exist.

A partial protection is sometimes mistaken for a complete one. sqlite3's execute refuses to run more than one statement, so an input that tries to append a second, destructive statement, x'; DROP TABLE drug; --, fails with "You can only execute one statement at a time" and the table survives. The UNION attack above needs only one statement, so this restriction does not stop it. And the same text passed to executescript, which runs any number of statements, drops the table: on the copy of the database, the drug table was gone afterwards. Some other drivers allow several statements in one call by default. Placeholders are the protection; everything else is an accident of the interface.

Identifiers cannot be parameters

Placeholders stand for values, not for names of tables or columns. con.execute("SELECT COUNT(*) FROM ?", ("drug",)) fails with a syntax error, because a table name is part of the statement's structure, which is fixed before any value is bound. When a table or column name genuinely has to vary, it must be checked against a fixed list of allowed names before it is inserted:

ALLOWED = {"person", "exam", "lab", "drug"}

def count_rows(table):
    if table not in ALLOWED:
        raise ValueError(f"unknown table {table!r}")
    return con.execute(f'SELECT COUNT(*) FROM "{table}"').fetchone()[0]

count_rows("lab")     # 7,435

Reading results into pandas

For analysis, the usual destination of a query result is a DataFrame. pandas.read_sql takes a query and a connection and does the execute, fetch and conversion in one call (pandas development team, 2024):

import pandas as pd

df = pd.read_sql("SELECT seqn, age, education, income_ratio FROM person WHERE age >= ?",
                 con, params=(18,))
df.shape    # (5856, 4)

params passes values to the driver's placeholders, in the driver's style, so the rule about string formatting applies here too. read_sql accepts a sqlite3 connection, an SQLAlchemy connection, or an ADBC connection; for other DB-API drivers, pandas' documentation says "only sqlite3 is supported" without SQLAlchemy (pandas development team, 2024).

The column types pandas chooses depend on the values that arrive, not on the table's declared types. seqn and age arrive as int64. education is declared INTEGER, but it is NULL for some adults, and NumPy integers cannot hold a missing value, so it arrives as float64, with 2.0 where the database has 2. For the 3,398 people under 18, every value of education is NULL, and the column arrives as object, holding None. The dtype_backend="numpy_nullable" option returns pandas' nullable integer type, Int64, which keeps integers as integers alongside missing values. The pandas Package explains why NaN cannot live in an integer array, and converts whole tables to the nullable types with convert_dtypes. The cleaning steps of Cleaning Data apply to data read from a database as much as to files.

For results too large for memory, chunksize=5000 makes read_sql return an iterator of DataFrames of up to 5,000 rows; the prescription table arrives as chunks of 5,000, 5,000 and 4,434 rows. The usual pattern is to aggregate each chunk and combine the results, or better, to push the aggregation into SQL and fetch only the summary (Aggregate Functions). In the opposite direction, DataFrame.to_sql(name, con) writes a DataFrame to a table, which is how Data Engineering loads raw files into SQLite before transforming them with SQL.

Transactions

A transaction groups statements so that they take effect together or not at all. The standard example is a transfer between two accounts, which must not stop after the withdrawal; in data work it is a cleaning step made of several updates, or a load that must not leave half a table behind. A transaction ends with COMMIT, which makes its changes permanent and visible to other connections, or ROLLBACK, which discards them.

DB-API connections start transactions implicitly. In sqlite3's default mode, which Python 3.12 named LEGACY_TRANSACTION_CONTROL, a transaction is opened automatically before an INSERT, UPDATE, DELETE or REPLACE and stays open until con.commit() or con.rollback() is called (Python Software Foundation, 2026). Changes not committed are invisible to other connections and are lost when the connection closes. On a file database, an update made through one connection and not yet committed is visible to that connection but not to a second connection to the same file; after rollback, the first connection no longer sees it either.

The connection works as a context manager that commits if the block finishes and rolls back if it raises an exception. On a copy of the database, a cleaning step that converts the coded values in the days column, 77777 (refused) and 99999 (don't know), to NULL in two updates, and fails between them:

try:
    with con:
        con.execute("UPDATE prescription SET days = NULL WHERE days = 77777")   # 4 rows
        raise RuntimeError("something failed between the two updates")
        con.execute("UPDATE prescription SET days = NULL WHERE days = 99999")   # never reached
except RuntimeError:
    pass

Before the block, 282 rows hold one of the codes; after the failed block, still 282, because the first update was rolled back with the rest. The same updates in a block that finishes leave none, and 407 rows with NULL days (the 282 converted and 125 that were missing already). Without the transaction, the failure would have left the four refused values converted and the 278 don't-know values not, a state that matches neither the old data nor the intended new data. The documentation adds that the context manager "neither implicitly opens a new transaction nor closes the connection" (Python Software Foundation, 2026); closing needs con.close() or contextlib.closing.

Since Python 3.12 the recommended way to control this is the autocommit argument of connect. autocommit=False gives the behavior PEP 249 specifies, in which a transaction is always open and must be committed explicitly; autocommit=True gives SQLite's own autocommit mode, in which each statement commits on its own (Python Software Foundation, 2026). Under autocommit=False and the default legacy mode, the context manager around each logical unit of work is the simplest correct pattern. Under autocommit=True, and under the older isolation_level=None, there is no transaction for the context manager to roll back: each statement commits as it runs, and the failed block above leaves the four refused values converted and 278 codes in place (Worked problem 2). Grouping statements then needs an explicit BEGIN.

This section covers one property of transactions, atomicity: a group of changes happens completely or not at all. The others, what concurrent connections may see of each other's work (isolation) and what survives a crash once a commit returns (durability), are subjects of database systems that this collection does not treat; the visibility of uncommitted changes to a second connection, above, is their simplest case.

SQLAlchemy

SQLAlchemy is a widely used Python library that sits above the DB-API drivers. Its lower layer, the Core, provides an engine, created from a URL that names the database and driver, which manages a pool of connections and smooths over differences between drivers. Its upper layer is an object-relational mapper that maps tables to Python classes, which matters more for applications than for analysis. For data work the engine is the part most often met, because pandas uses it to reach databases other than SQLite:

import sqlalchemy as sa

engine = sa.create_engine("sqlite:///nhanes.db")        # postgresql+psycopg://user@host/db, ...
with engine.connect() as c:
    adults = c.execute(sa.text("SELECT COUNT(*) FROM person WHERE age >= :lo"),
                       {"lo": 18}).scalar_one()          # 5,856
    by_sex = pd.read_sql(sa.text("SELECT sex, COUNT(*) AS n FROM person GROUP BY sex"), c)

sa.text marks a string as SQL and uses named placeholders whatever the driver's own style, one of the differences SQLAlchemy hides. Changing the URL is enough to run the same code against PostgreSQL or MySQL, provided the SQL itself is portable, which the dialect notes throughout this topic are meant to help with.

Worked problems

The three problems test the article's recommendations against the alternatives people try: escaping quotes instead of using placeholders, relying on the connection's transaction setting, and combining chunk summaries by hand. The review-pass block of sql-queries-in-python.py checks each with Python 3.13.5, SQLite 3.49.1 and pandas 2.2.3.

Problem 1 (escaping quotes is not a substitute for placeholders). A common repair of the unsafe find_drug doubles every single quote in the input before formatting it into the string, which is how SQL writes a quote inside a literal. Does it stop the attacks, and is it safe in general?

The string case. Doubling quotes does stop the three inputs of the article: they return 1, 0 and 0 rows, the same as with a placeholder. The input x' OR '1'='1 becomes x'' OR ''1''=''1, which inside the quotes of the query is a single string literal, a drug name that does not exist. As long as the value goes inside a quoted literal and quotes are the only character that can end it, the escaping holds.

The numeric case. The second condition is the weak one. A query that looks up a person by number has no quotes around the value: "SELECT seqn, age FROM person WHERE seqn = %s" % value. Given the input 0 OR 1=1, the query becomes WHERE seqn = 0 OR 1=1 and returns all 9,254 people. The input contains no quote, so doubling quotes changes nothing, and the escaped query returns all 9,254 as well. With a placeholder, the input is bound as one text value, '0 OR 1=1', which equals no person number, and the query returns 0 rows.

Why the placeholder always works. Escaping tries to predict how the parser will read the value, and the prediction depends on the context: inside quotes, outside quotes, inside an identifier, in a dialect where a backslash escapes the next character inside a string literal, as MySQL's does unless its NO_BACKSLASH_ESCAPES mode is set (MySQL, n.d.), so that an input containing a backslash before a quote can undo the doubling. A placeholder removes the prediction, because the statement is parsed before the value exists, so no character of the value can be read as SQL in any context. That is why the sqlite3 documentation gives the rule without exception.

Problem 2 (what the transaction setting changes). Run the failing cleaning step of the section on transactions, where the error comes after the first update and before the second, under each of the connection's transaction settings, and explain each result.

Results. The number of coded values left in days after the failed block, out of 282 before it:

Connection setting Coded values left Why
default (legacy transaction control) 282 the first UPDATE opened a transaction; the context manager rolled it back
autocommit=False (Python 3.12 and later) 282 a transaction is always open; the context manager rolled it back
autocommit=True (Python 3.12 and later) 278 each statement committed at once; the 4 refused values stayed converted
isolation_level=None 278 the older spelling of SQLite's own autocommit mode, with the same effect

Explanation. The context manager does only two things: it commits if the block finishes and rolls back if it raises. Rolling back undoes the changes made since the transaction began. In the first two settings a transaction was open when the first update ran, so the rollback undoes it. In the last two, SQLite commits each statement as it completes, so by the time the error is raised there is nothing uncommitted to undo, and the data are left in the mixed state the article warned about: four codes converted, 278 not. The same code is therefore atomic or not depending on a connection argument that may be set far away from it. Where atomicity matters, either keep a setting in which the driver opens transactions, or open one explicitly with BEGIN and end it with COMMIT or ROLLBACK.

Problem 3 (combining summaries of chunks). Reading the prescription table with chunksize=5000 gives three chunks. How should the mean number of days of use be combined from them, leaving out the codes 77777 and 99999 and the missing values?

Approach. If chunk $c$ has $n_c$ usable values with mean $\bar{x}_c$, the sum of its values is $n_c \bar{x}_c$, so the mean of all the values is

$$\bar{x} = \frac{\sum_c n_c \bar{x}_c}{\sum_c n_c},$$

the chunk means weighted by their sizes. The plain mean of the chunk means equals it only when every chunk has the same number of usable values, or the chunk means are all equal.

Results. The chunks have 5,000, 5,000 and 4,434 rows, of which 4,874, 4,837 and 4,316 hold a usable number of days (14,027 in all, the 14,434 prescriptions less the 407 whose days are NULL once the codes are removed). Their means are 2,271.71, 2,194.82 and 2,115.09 days. Weighted by size they give 2,197.01, which is SQL's AVG(days) over the same values. The plain mean of the three means is 2,193.87. The error is small here because the chunks are of similar size, but it has no bound in general: a last chunk of 10 rows would count as much as each chunk of 5,000. Carrying the sum and the count from each chunk, rather than the mean, makes the combination exact, and the same holds for any statistic built from sums, such as the variance through sums of squares, with the numerical caution of Aggregate Functions. Medians and other quantiles cannot be combined this way at all.

Open questions

  • How do other drivers treat multiple statements and transactions? Repeating the injection and transaction experiments with psycopg against PostgreSQL and mysql-connector-python against MySQL, in containers pinned to stated versions, would show which of the protections and defaults described here for sqlite3 carry over.
  • Is read_sql with chunksize faster than fetching with a cursor, or only lighter on memory? Timing both, 30 runs each, on the prescription table enlarged 10 to 100 times, with peak memory recorded, would settle when chunking pays.
  • Which pandas type does each SQLite column become under each dtype_backend? Reading every table of the database with the default, numpy_nullable and pyarrow backends, and comparing the types with the declared ones, would give a complete map instead of the three columns examined here.

Where it leads

From Python a query is a constant string with placeholders, its values passed separately; results arrive as tuples, rows or DataFrames; and changes are grouped in transactions so that a failure leaves the database as it was. This article closes the topic. The next topic of the collection, Introduction to Data Wrangling, turns from retrieving data to preparing it: summarizing by groups, reshaping, cleaning and combining, much of which can be done in SQL as well as in pandas.

Summary of the pattern

  • Connect, preferably in a with block or with contextlib.closing, and keep credentials out of the code.
  • Write the query as a constant string with placeholders; pass every value as a parameter; never format data into SQL.
  • Fetch with fetchall for small results, iterate or use chunksize for large ones, and let SQL do the aggregation when only a summary is needed.
  • Read into pandas with read_sql, and check the column types it produced.
  • Wrap changes in a transaction, so that a failure leaves the database as it was.

The results in this article are produced by tools/experiments/data-science/sql-queries-in-python.py in the site's repository, which runs the injection examples on an in-memory copy of the database. It was run with Python 3.13 (SQLite 3.49.1, pandas 2.2.3) and, for the SQLAlchemy section, with Python 3.11 (SQLite 3.38.4, pandas 3.1.1, SQLAlchemy 2.0.43), with the same results apart from the autocommit attribute, which Python 3.11 does not have. A rerun on 23 November 2026 with Python 3.13.5, SQLite 3.49.1, pandas 3.1.1 and SQLAlchemy 2.0.43 gave the same results.

References

Reviewed: verified, 23 Nov 2026 · citations checked, 23 Nov 2026 · editorial review, 23 Nov 2026 · 5 revisions