Sub topic 2
Connecting with sqlite3 and SQLAlchemy
pandas does not talk to a database by itself. It needs a connection object that can send SQL and return rows. This chapter covers the two connection types you will use most: a sqlite3 connection and a SQLAlchemy engine.
This chapter assumes you know basic Python (functions and context managers), basic pandas (DataFrame, columns, dtypes) and basic SQL (SELECT, WHERE, GROUP BY, JOIN).
What pandas accepts
The read_sql_* functions take a connectable as their second argument. In practice that is one of two things:
- A DBAPI connection. DBAPI is Python's standard interface for database drivers. The
sqlite3module in the standard library follows it. pandas supports this form for SQLite only. - A SQLAlchemy engine or connection. SQLAlchemy is a library that gives one interface to many databases, such as PostgreSQL, MySQL and SQLite.
Connecting with sqlite3
sqlite3.connect opens a database file, and creates it if it does not exist. The next script creates shop.db and loads a query result. The other chapters reuse this file.
import sqlite3
from contextlib import closing
import pandas as pd
with closing(sqlite3.connect("shop.db")) as conn:
conn.executescript("""
DROP TABLE IF EXISTS orders;
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');
""")
conn.commit()
df = pd.read_sql_query("SELECT id, customer, total FROM orders", conn)
print(df)The script wraps the connection in contextlib.closing. A sqlite3 connection used in a plain with block does not close at the end. It only commits or rolls back the open transaction, so the file handle stays open. closing calls conn.close() for you.
A relative path such as "shop.db" resolves against the current working directory. If the file is not where you expect, SQLite creates a new empty database. The query then fails with no such table, which is a confusing symptom of a wrong path.
Connecting with a SQLAlchemy engine
An engine is an object that knows how to reach a database and manages a pool of connections. You create it once from a URL:
dialect+driver://username:password@host:port/databaseSome examples:
| Database | URL |
|---|---|
| SQLite, relative path | `sqlite:///shop.db` |
| SQLite, absolute path (Linux/macOS) | `sqlite:////home/me/shop.db` |
| SQLite, in memory | `sqlite://` |
| PostgreSQL with psycopg2 | `postgresql+psycopg2://user:secret@localhost:5432/shop` |
| MySQL with PyMySQL | `mysql+pymysql://user:secret@localhost:3306/shop` |
For SQLite, three slashes mean a relative path and four mean an absolute path on Unix. The driver package, such as psycopg2 or pymysql, must be installed separately.
import pandas as pd
from sqlalchemy import create_engine, text
engine = create_engine("sqlite:///shop.db")
with engine.connect() as connection:
df = pd.read_sql_query(text("SELECT id, customer, total FROM orders"), connection)
print(df)create_engine does not open a connection. The first real connection happens inside engine.connect(). A wrong password or host therefore shows up at that line, not at create_engine.
The with engine.connect() block returns the connection to the pool when it ends. Wrapping the SQL in text() marks it as a literal SQL string. SQLAlchemy 2.x requires this for plain strings passed to its own execute. pandas also accepts a plain string, but text() lets you use named parameters such as :name, which a later chapter covers.
Choosing between them
| Situation | Use |
|---|---|
| A quick script against one SQLite file | `sqlite3` connection |
| Any database other than SQLite | SQLAlchemy engine |
| You need `read_sql_table` | SQLAlchemy engine |
| You want one code path for several databases | SQLAlchemy engine |
read_sql_table reads a table by name. It inspects the database schema to do so, and that needs SQLAlchemy. The same applies to a few other schema-aware features.
Keep credentials out of code
Do not write passwords into your source files. Read the URL from an environment variable instead:
import os
from sqlalchemy import create_engine
engine = create_engine(os.environ.get("DATABASE_URL", "sqlite:///shop.db"))This script falls back to the local SQLite file when DATABASE_URL is not set. The same code then works on your laptop and on a server.
Exercise
You run create_engine("postgresql+psycopg2://user:wrongpass@localhost/shop") and no error appears. A line later, engine.connect() raises an authentication error. Why did the first call succeed, and what is the cleanest way to run a query on this engine with pandas?
Show answer
create_engine only builds the engine and its connection pool. It does not open a connection, so credentials are first checked in engine.connect(). To query, open the connection in a with engine.connect() as connection: block and pass connection (or the engine itself) to pd.read_sql_query. The block returns the connection to the pool when it ends.