Databases in Python: sqlite3, Safe Queries and SQLAlchemy
results.csv that two scripts keep overwriting. Then someone asks which run with a learning rate below 0.05 had the best validation accuracy, and you start scrolling. A database file answers that in one line and is still there tomorrow. This lesson is the Python side of that: how sqlite3 talks to a database, how to pass values safely, how to stop a failed write from leaving half the data behind, and where pandas and SQLAlchemy fit.After this lesson, you will be able to:
- Create a SQLite table from Python, insert rows and query them with sqlite3
- Pass values with ? placeholders and explain why string formatting lets an attacker rewrite the query
- Read rows as dict-like objects with row_factory
- Commit, roll back and close a connection correctly, knowing what `with` does and does not do
- Turn on foreign key enforcement and move data between SQLite and pandas with read_sql and to_sql
- Read and write rows through a SQLAlchemy 2.0 model and Session
Before you start
INSERT (add a row) and SELECT ... WHERE (read the rows that match). The SQL stays short, and each other statement shape is explained in a line where it first appears: CREATE TABLE, CHECK, ORDER BY ... LIMIT, COUNT(*), ROUND, REFERENCES, PRAGMA and LIKE. Joins, grouping and indexes are not needed here. They are taught in the SQL track, starting with Your First SQL Query and Filtering & Sorting Data, and the Python around the SQL is the subject of this lesson.Everything below runs on an in-memory database, and each cell builds its own data.
#Connection, Cursor and Commit
sqlite3, a driver for SQLite, a database that lives in a single file (or, with the name ":memory:", in RAM and nowhere else). Three objects do all the work.| Object | What it is | What you call on it |
|---|---|---|
| connection | an open line to the database; it owns the current transaction | commit(), rollback(), close() |
| cursor | sends one statement and holds its result rows | execute(), fetchone(), fetchall() |
| transaction | a batch of changes that are not permanent yet | ends with commit() or rollback() |
commit().import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("""
CREATE TABLE runs (
id INTEGER PRIMARY KEY,
model TEXT NOT NULL,
lr REAL NOT NULL,
epochs INTEGER NOT NULL,
val_acc REAL NOT NULL,
owner TEXT NOT NULL
)
""")
cur.execute(
"INSERT INTO runs (model, lr, epochs, val_acc, owner) VALUES (?, ?, ?, ?, ?)",
("resnet18", 0.01, 10, 0.912, "asha"),
)
conn.commit()
cur.execute("SELECT model, lr, val_acc FROM runs WHERE val_acc > ?", (0.9,))
print(cur.fetchall())
print(cur.description[0][0])
conn.close()Output:
[('resnet18', 0.01, 0.912)]
model
CREATE TABLE names the columns and their types. PRIMARY KEY gives each row a unique id, and NOT NULL forbids an empty value. Each row comes back as a tuple, in the column order you asked for, and cur.description lists the column names. The ? marks are placeholders: the values travel in a separate tuple instead of being typed into the SQL. They get a section of their own below.#The Insert That Seemed to Vanish
The first surprise most people meet is a row they inserted and cannot find. Two connections to the same file make it visible. The cell writes its own temporary file first.
import os, sqlite3, tempfile
path = os.path.join(tempfile.mkdtemp(), "runs.db")
writer = sqlite3.connect(path)
writer.execute("CREATE TABLE runs (id INTEGER PRIMARY KEY, val_acc REAL)")
writer.commit()
writer.execute("INSERT INTO runs (val_acc) VALUES (0.91)") # no commit yet
reader = sqlite3.connect(path) # a second connection
print("before commit:", reader.execute("SELECT COUNT(*) FROM runs").fetchone())
writer.commit()
print("after commit: ", reader.execute("SELECT COUNT(*) FROM runs").fetchone())
writer.close()
reader.close()Output:
before commit: (0,)
after commit: (1,)
commit(). If the script ends or calls close() without a commit, the pending change is thrown away. A script that "saves" results and finds an empty table next time has usually forgotten this one call.conn.execute(...) is a shortcut that makes a cursor, runs the statement and returns the cursor, which is why the cell above could chain .fetchone(). COUNT(*) is the SQL way to ask "how many rows".#Parameters, Not String Formatting
runs table with four rows and tries it. It prints the SQL it actually sends.import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("""
CREATE TABLE runs (
id INTEGER PRIMARY KEY,
model TEXT NOT NULL,
lr REAL NOT NULL,
epochs INTEGER NOT NULL,
val_acc REAL NOT NULL CHECK (val_acc BETWEEN 0 AND 1),
owner TEXT NOT NULL
)
""")
rows = [
("resnet18", 0.010, 10, 0.912, "asha"),
("resnet18", 0.100, 10, 0.874, "asha"),
("resnet50", 0.010, 20, 0.934, "ravi"),
("vit-small", 0.001, 30, 0.941, "ravi"),
]
conn.executemany(
"INSERT INTO runs (model, lr, epochs, val_acc, owner) VALUES (?, ?, ?, ?, ?)", rows
)
conn.commit()
def runs_for_owner_unsafe(owner):
sql = f"SELECT model, val_acc FROM runs WHERE owner = '{owner}'"
print(sql)
return conn.execute(sql).fetchall()
print(runs_for_owner_unsafe("asha"))
print()
print(runs_for_owner_unsafe("' OR '1'='1"))Output:
SELECT model, val_acc FROM runs WHERE owner = 'asha'
[('resnet18', 0.912), ('resnet18', 0.874)]
SELECT model, val_acc FROM runs WHERE owner = '' OR '1'='1'
[('resnet18', 0.912), ('resnet18', 0.874), ('resnet50', 0.934), ('vit-small', 0.941)]
CHECK (val_acc BETWEEN 0 AND 1) in the table definition makes the database reject any row whose accuracy is outside 0 to 1. With a normal name the query works. With ' OR '1'='1 as the "name", the first quote closes the string early, and OR '1'='1' is a condition that is true for every row. The query now returns Ravi's runs to Asha. This is SQL injection: input that was meant to be data has become part of the SQL. The database cannot tell which part of the text you wrote and which part the user typed.x'; DROP TABLE runs; --. That one does not work in sqlite3, because execute runs exactly one statement.import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE runs (id INTEGER PRIMARY KEY, owner TEXT)")
conn.execute("INSERT INTO runs (owner) VALUES ('asha')")
attack = "x'; DROP TABLE runs; --"
try:
conn.execute(f"SELECT * FROM runs WHERE owner = '{attack}'")
except sqlite3.ProgrammingError as e:
print(e)
print(conn.execute("SELECT COUNT(*) FROM runs").fetchone())Output:
You can only execute one statement at a time.
(1,)
OR trick above needs only one statement. Some other database drivers do accept several statements in one call, and there the stacked version works. (Before Python 3.11 this error was a sqlite3.Warning instead; the lesson runs on 3.12, where it is a ProgrammingError.)? where each value goes and pass the values as a tuple. The driver sends the query and the values separately, so a value is always just a value.import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE runs (id INTEGER PRIMARY KEY, model TEXT, lr REAL, val_acc REAL, owner TEXT)")
conn.executemany("INSERT INTO runs (model, lr, val_acc, owner) VALUES (?, ?, ?, ?)", [
("resnet18", 0.010, 0.912, "asha"),
("resnet18", 0.100, 0.874, "asha"),
("resnet50", 0.010, 0.934, "ravi"),
("vit-small", 0.001, 0.941, "ravi"),
])
def runs_for_owner(owner):
return conn.execute(
"SELECT model, val_acc FROM runs WHERE owner = ?", (owner,)
).fetchall()
print(runs_for_owner("asha"))
print(runs_for_owner("' OR '1'='1"))
# Named placeholders take a dict, which reads better with several values
print(conn.execute(
"SELECT model FROM runs WHERE lr <= :max_lr AND val_acc >= :min_acc",
{"max_lr": 0.01, "min_acc": 0.93},
).fetchall())Output:
[('resnet18', 0.912), ('resnet18', 0.874)]
[]
[('resnet50',), ('vit-small',)]
executemany (used above to insert) runs one statement for a whole list of value tuples.A placeholder stands in for a value. Which of these can a ? placeholder replace in a query?
#Rows That Behave Like Dicts
row[2] and hoping you counted the columns right. Set row_factory = sqlite3.Row on the connection and each row becomes an object you can index by name or by position.import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE runs (id INTEGER PRIMARY KEY, model TEXT, lr REAL, val_acc REAL)")
conn.executemany("INSERT INTO runs (model, lr, val_acc) VALUES (?, ?, ?)", [
("resnet18", 0.010, 0.912),
("resnet18", 0.100, 0.874),
("resnet50", 0.010, 0.934),
("vit-small", 0.001, 0.941),
])
print(conn.execute("SELECT model, val_acc FROM runs WHERE id = 1").fetchone())
conn.row_factory = sqlite3.Row
row = conn.execute("SELECT model, lr, val_acc FROM runs WHERE id = 3").fetchone()
print(row["model"], row[2], row.keys())
print(dict(row))
top_two = conn.execute("SELECT model, val_acc FROM runs ORDER BY val_acc DESC LIMIT 2")
print([dict(r) for r in top_two])Output:
('resnet18', 0.912)
resnet50 0.934 ['model', 'lr', 'val_acc']
{'model': 'resnet50', 'lr': 0.01, 'val_acc': 0.934}
[{'model': 'vit-small', 'val_acc': 0.941}, {'model': 'resnet50', 'val_acc': 0.934}]
dict(row) gives a plain dictionary, which is what you want to hand to JSON or to code that does not know about sqlite3. Name access also survives a change to the query: add a column to the SELECT and row["val_acc"] still finds the right value, while row[2] may now be something else.ORDER BY val_acc DESC sorts the rows from highest to lowest, and LIMIT 2 keeps only the first two, so LIMIT 1 gives you the single best run.#Transactions and What with Really Does
rollback() discards everything since the last commit. The connection is a context manager that does this for you: leaving a with conn: block normally commits, and leaving it because of an exception rolls back and lets the exception continue.import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("""
CREATE TABLE runs (
id INTEGER PRIMARY KEY,
model TEXT NOT NULL,
val_acc REAL NOT NULL CHECK (val_acc BETWEEN 0 AND 1)
)
""")
with conn:
conn.execute("INSERT INTO runs (model, val_acc) VALUES ('mlp', 0.80)")
print("committed, rows:", conn.execute("SELECT COUNT(*) FROM runs").fetchone()[0])
try:
with conn:
conn.execute("INSERT INTO runs (model, val_acc) VALUES ('cnn', 0.88)")
conn.execute("INSERT INTO runs (model, val_acc) VALUES ('bad', 7.5)")
except sqlite3.IntegrityError as e:
print("rolled back:", e)
print("rows now:", conn.execute("SELECT COUNT(*) FROM runs").fetchone()[0])Output:
committed, rows: 1
rolled back: CHECK constraint failed: val_acc BETWEEN 0 AND 1
rows now: 1
cnn row was valid, and it was inserted before the bad one failed. It is gone anyway, because both inserts were one transaction. The CHECK in the table definition is what rejected 7.5. A constraint turns bad data into an exception at write time, instead of a wrong number you find in a plot a month later.with block ends the transaction, but it does not close the connection.After a with conn: block finishes normally, what does conn.execute('SELECT 1') do?
closing calls close() when its block ends, and the inner with conn: handles the commit or rollback.import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:")) as conn:
with conn:
conn.execute("CREATE TABLE t (x INTEGER)")
conn.execute("INSERT INTO t VALUES (1)")
print(conn.execute("SELECT x FROM t").fetchall())
try:
conn.execute("SELECT 1")
except sqlite3.ProgrammingError as e:
print("after closing:", e)Output:
[(1,)]
after closing: Cannot operate on a closed database.
with idea from the context-managers lesson, applied to a resource with two jobs: ending a transaction and closing a connection.#Foreign Keys Are Off by Default
REFERENCES runs(id) declares that link, executescript runs several ;-separated statements in one call, and PRAGMA reads or sets a SQLite setting. In SQLite, declaring the foreign key is not enough. The check is off unless you turn it on, which surprises people who expect the constraint to work.import sqlite3
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE runs (id INTEGER PRIMARY KEY, model TEXT);
CREATE TABLE metrics (
run_id INTEGER REFERENCES runs(id),
step INTEGER,
loss REAL
);
""")
print("enforced:", conn.execute("PRAGMA foreign_keys").fetchone()[0])
conn.execute("INSERT INTO metrics VALUES (99, 1, 0.5)")
print("orphan accepted:", conn.execute("SELECT * FROM metrics").fetchall())
strict = sqlite3.connect(":memory:")
strict.execute("PRAGMA foreign_keys = ON")
strict.executescript("""
CREATE TABLE runs (id INTEGER PRIMARY KEY, model TEXT);
CREATE TABLE metrics (run_id INTEGER REFERENCES runs(id), step INTEGER, loss REAL);
""")
try:
strict.execute("INSERT INTO metrics VALUES (99, 1, 0.5)")
except sqlite3.IntegrityError as e:
print("IntegrityError:", e)Output:
enforced: 0
orphan accepted: [(99, 1, 0.5)]
IntegrityError: FOREIGN KEY constraint failed
PRAGMA foreign_keys = ON (put it in whatever function opens your connections). And it must run before any data-changing statement, because inside an open transaction the pragma is silently ignored.You open a connection, run PRAGMA foreign_keys = ON, then close it and open a new connection to the same database file. Is foreign key checking on in the new connection?
#pandas and SQL
pd.read_sql, and writes a DataFrame into a table with DataFrame.to_sql. Both accept the same ? parameters, so the safety rules carry over.import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE runs (id INTEGER PRIMARY KEY, model TEXT, lr REAL, val_acc REAL)")
conn.executemany("INSERT INTO runs (model, lr, val_acc) VALUES (?, ?, ?)", [
("resnet18", 0.010, 0.912),
("resnet18", 0.100, 0.874),
("resnet50", 0.010, 0.934),
("vit-small", 0.001, 0.941),
])
conn.commit()
df = pd.read_sql(
"SELECT model, lr, val_acc FROM runs WHERE val_acc >= ? ORDER BY val_acc DESC",
conn,
params=(0.9,),
)
print(df)
df["val_err"] = 1 - df["val_acc"]
df[["model", "lr", "val_err"]].to_sql("run_summary", conn, if_exists="replace", index=False)
print(conn.execute("SELECT model, ROUND(val_err, 3) FROM run_summary").fetchall())
try:
df[["model"]].to_sql("run_summary", conn, index=False)
except ValueError as e:
print("ValueError:", e)Output:
model lr val_acc
0 vit-small 0.001 0.941
1 resnet50 0.010 0.934
2 resnet18 0.010 0.912
[('vit-small', 0.059), ('resnet50', 0.066), ('resnet18', 0.088)]
ValueError: Table 'run_summary' already exists.
ROUND(val_err, 3) rounds the stored value to three decimals for display. Filter in the WHERE clause, not afterwards in pandas. The database sends back only the matching rows, so a table far larger than memory is still fine as long as the question is narrow. Pulling a whole table into a DataFrame and then filtering throws that advantage away. (read_sql also takes chunksize= to stream a big result in pieces.)to_sql refuses to overwrite an existing table by default. Pass if_exists="replace" to drop and recreate it, or "append" to add rows. Pass index=False unless you want the DataFrame's row labels saved as an extra column called index. A plain sqlite3 connection is what pandas supports for SQLite; for PostgreSQL and other databases pandas expects a SQLAlchemy engine, which is the next section.#One SQLAlchemy Example
sqlite3 is a driver: you write SQL and it executes it. SQLAlchemy sits above drivers. It gives you one API that works over SQLite, PostgreSQL and others, and an optional ORM (object-relational mapper) that maps a Python class to a table and an instance to a row. Use it when a project might change databases or has many tables. For a script that logs runs to one file, plain sqlite3 is enough.engine.execute(...). That method no longer exists.from sqlalchemy import create_engine, text
engine = create_engine("sqlite:///:memory:")
try:
engine.execute(text("SELECT 1"))
except AttributeError as e:
print("AttributeError:", e)
with engine.connect() as conn:
conn.execute(text("CREATE TABLE runs (id INTEGER PRIMARY KEY, model TEXT, val_acc REAL)"))
conn.execute(
text("INSERT INTO runs (model, val_acc) VALUES (:model, :acc)"),
[{"model": "resnet18", "acc": 0.912}, {"model": "vit-small", "acc": 0.941}],
)
conn.commit()
result = conn.execute(text("SELECT model, val_acc FROM runs WHERE val_acc > :t"), {"t": 0.92})
print(result.all())Output:
AttributeError: 'Engine' object has no attribute 'execute'
[('vit-small', 0.941)]
engine.connect() and run statements on that. SQL goes inside text(...), with :name placeholders and values passed as a dict, which keeps the injection protection. And nothing is saved until you call conn.commit(): leaving the block without it discards the changes, the same pending-transaction rule you met at the start.Session collects the objects you add and writes them on commit().from sqlalchemy import create_engine, select, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class Run(Base):
__tablename__ = "runs"
id: Mapped[int] = mapped_column(primary_key=True)
model: Mapped[str]
lr: Mapped[float]
val_acc: Mapped[float]
def __repr__(self) -> str:
return f"Run({self.model}, lr={self.lr}, val_acc={self.val_acc})"
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add_all([
Run(model="resnet18", lr=0.01, val_acc=0.912),
Run(model="resnet50", lr=0.01, val_acc=0.934),
Run(model="vit-small", lr=0.001, val_acc=0.941),
])
session.commit()
best = session.scalars(select(Run).order_by(Run.val_acc.desc())).first()
print(best)
for run in session.scalars(select(Run).where(Run.lr <= 0.01, Run.val_acc > 0.92)):
print(run.model, run.val_acc)
print(round(session.scalar(select(func.avg(Run.val_acc))), 3))Output:
Run(vit-small, lr=0.001, val_acc=0.941)
resnet50 0.934
vit-small 0.941
0.929
Run is an ordinary class whose attributes are columns. select(Run).where(...) builds the query in Python, with Run.val_acc > 0.92 standing in for the SQL condition, and session.scalars(...) runs it and returns Run objects. Values are bound as parameters for you. The cost is another layer to learn, and for analysis you will often still drop to SQL or pandas.#Common Mistakes
#A placeholder where a name should go
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE runs (id INTEGER, val_acc REAL)")
conn.execute("CREATE TABLE evals (id INTEGER, val_acc REAL)")
try:
conn.execute("SELECT * FROM ?", ("runs",))
except sqlite3.OperationalError as e:
print("OperationalError:", e)
ALLOWED = {"runs", "evals"}
def count_rows(table):
if table not in ALLOWED:
raise ValueError(f"unknown table: {table!r}")
return conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
print(count_rows("runs"))
try:
count_rows("runs; DROP TABLE runs")
except ValueError as e:
print(e)Output:
OperationalError: near "?": syntax error
0
unknown table: 'runs; DROP TABLE runs'
Placeholders carry values only. When a table or column name must vary, compare it against a fixed set of allowed names, and only then put it into the SQL.
#A placeholder inside quotes
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE runs (id INTEGER, model TEXT)")
conn.execute("INSERT INTO runs VALUES (1, 'resnet18')")
try:
conn.execute("SELECT * FROM runs WHERE model LIKE '%?%'", ("resnet",))
except sqlite3.ProgrammingError as e:
print(e)
print(conn.execute("SELECT * FROM runs WHERE model LIKE ?", ("%resnet%",)).fetchall())Output:
Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.
[(1, 'resnet18')]
LIKE matches text against a pattern, where % stands for any run of characters. Inside quotes, ? is just a question mark in a string. Leave the placeholder bare and put the % wildcards in the value instead.#Saving the DataFrame index by accident
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
df = pd.DataFrame({"model": ["a", "b"], "val_acc": [0.9, 0.8]}).sort_values("val_acc")
df.to_sql("with_index", conn)
df.to_sql("without_index", conn, index=False)
print([c[1] for c in conn.execute("PRAGMA table_info(with_index)")])
print([c[1] for c in conn.execute("PRAGMA table_info(without_index)")])Output:
['index', 'model', 'val_acc']
['model', 'val_acc']
PRAGMA table_info(name) lists a table's columns. After a sort or a filter the index holds meaningless leftover row numbers, and by default to_sql writes them into the table as a column.#Try It
log_run must insert inside with conn: using placeholders, so a value that breaks the CHECK leaves the table unchanged. best_run must return the best row for a model as a dictionary, or None when the model has no runs. Your output should match the lines at the bottom of the starter code.Tests: Prints the rejection message, the best resnet18 run, then None twice.
Now find and fix the injection in this model-registry lookup. A caller who passes the right kind of string can list models that are in production.
find_stage should return only the row whose name matches. Today, find_stage("' OR '1'='1") returns every model, including the production one. Change the function so that input is treated as data.
[('resnet18', 'staging')]
[]#Recap
sqlite3 connection holds your changes in a pending transaction until you call commit(), and a second connection sees nothing before that. A cursor sends a statement and holds its rows, and conn.execute() makes one for you.? or :name placeholders, never into the SQL string with an f-string, because a value like ' OR '1'='1 otherwise becomes part of the query. Placeholders cannot stand in for table or column names. In sqlite3 the stacked DROP TABLE attack fails because execute runs one statement, but the OR attack works.row_factory = sqlite3.Row gives dict-like rows. with conn: commits or rolls back but does not close, so use contextlib.closing to close as well. Foreign keys are checked only after PRAGMA foreign_keys = ON on each connection. pd.read_sql and to_sql move data to and from pandas, and in SQLAlchemy 2.0 you run SQL on engine.connect() with text(...) and call commit() yourself.What does this print? conn = sqlite3.connect(':memory:') conn.execute('CREATE TABLE t (x INTEGER NOT NULL)') try: with conn: conn.execute('INSERT INTO t VALUES (1)') conn.execute('INSERT INTO t VALUES (NULL)') except sqlite3.IntegrityError: pass print(conn.execute('SELECT COUNT(*) FROM t').fetchone()[0])
#Going Further
json.dumps) is a common alternative to one column per parameter, and the same placeholder rules apply. Migrations, connection pools and PostgreSQL drivers belong to larger applications.