Sub topic 2
Connecting with sqlite3 and SQLAlchemy
Every pandas SQL reader needs a connection object as its second argument. This chapter covers the connection types pandas accepts, how to build each one, and how to manage its lifetime. It also covers which mistakes produce warnings and which produce errors.
Prerequisites
This chapter assumes you know:
- Basic Python, including functions and context managers (
withblocks). - Basic pandas: what a DataFrame is, and how columns and dtypes work.
- Basic SQL:
SELECT,WHERE,GROUP BY,JOIN.
You also need pandas 2.0 or later. Install SQLAlchemy 2.0 or later for the second half of the chapter:
pip install pandas sqlalchemyThe sqlite3 module ships with Python and needs no installation.
What pandas accepts as a connection
pandas does not talk to databases itself. It hands your query to a Python database driver and builds a DataFrame from the rows that come back. The con argument tells pandas which driver path to use. It accepts three kinds of object:
| Object | Where it comes from | Support level |
|---|---|---|
| `sqlite3.Connection` | Python standard library | Supported, SQLite only |
| SQLAlchemy `Engine` or `Connection` | `sqlalchemy.create_engine(...)` | Supported, any database SQLAlchemy has a dialect for |
| URL string | A SQLAlchemy URL such as `"sqlite:///shop.db"` | Supported by `read_sql_query`, `read_sql_table` and `read_sql`. pandas builds an engine from it |
Connection objects from other drivers, such as a raw psycopg2 or pymysql connection, still work in many cases. pandas does not test them, though, and it warns you.
The rest of this chapter uses one small SQLite file, shop.db. SQLite stores a whole database in one file, so you need no server to follow along.
Connecting with sqlite3
sqlite3.connect(path) opens the database file at path. If the file does not exist, SQLite creates an empty one. Pass the resulting connection to any pandas reader.
The script below builds shop.db and reads from it. It uses the same orders table as the other chapters.
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 output is:
id customer total
0 1 Ada 120.5
1 2 Grace 80.0
2 3 Ada 200.0Closing a sqlite3 connection correctly
A sqlite3.Connection can be used in a with block, but that block does not close the connection. It only commits the transaction when the block succeeds and rolls it back when the block raises an exception. The connection stays open afterwards. That is why the example wraps the connection in contextlib.closing, which calls close() on exit.
A wrong path creates an empty database
SQLite creates a missing file instead of raising an error. If you mistype the path, sqlite3.connect("shopp.db") succeeds and gives you an empty database. The failure shows up one step later, when pandas runs the query:
import sqlite3
from contextlib import closing
import pandas as pd
with closing(sqlite3.connect("shopp.db")) as conn:
try:
pd.read_sql_query("SELECT * FROM orders", conn)
except Exception as exc:
print(type(exc).__name__, exc)pandas wraps the driver error in pandas.errors.DatabaseError, and the message ends with no such table: orders. That message nearly always means the connection points at the wrong file, not that the table is missing from the right file. Look for a stray empty .db file in your working directory. SQLite resolves relative paths against the current working directory, not against your script's location.
To make a wrong path fail at connection time, open the file in read-only mode with a URI:
import sqlite3
from contextlib import closing
import pandas as pd
with closing(sqlite3.connect("file:shop.db?mode=ro", uri=True)) as conn:
print(pd.read_sql_query("SELECT COUNT(*) AS n FROM orders", conn))With mode=ro, a missing file raises sqlite3.OperationalError: unable to open database file right away. Writes through that connection also fail, which is what you want for an analysis script.
In-memory databases
sqlite3.connect(":memory:") creates a database that lives only in RAM and disappears when the connection closes. Each new connection to ":memory:" gets its own separate, empty database. Tables created through one connection are invisible to another. This is useful in tests, but keep it in mind if you open several connections in one program.
Parameter style
A driver follows one placeholder style for query parameters. sqlite3 uses ? (the "qmark" style). Other drivers use %s, :name, or %(name)s. This matters for the next chapter on parameters, and it is one reason to learn the SQLAlchemy route, which gives you one style across databases.
Connecting with SQLAlchemy
SQLAlchemy is a Python library that sits between your code and many different database drivers. You give it a URL, and it picks the right dialect and driver. For pandas, the benefits are:
- Support for PostgreSQL, MySQL, SQL Server, Oracle, and others through one interface.
- Connection pooling, which reuses open connections instead of reconnecting on every call.
read_sql_table, which works only with SQLAlchemy (see the chapter on whole tables).
Engine URLs
You build everything from create_engine(url). The URL has this shape:
dialect+driver://username:password@host:port/databaseThe +driver part is optional, and SQLAlchemy picks a default driver when you omit it. The driver must be installed separately.
| Database | Example URL | Driver package |
|---|---|---|
| SQLite, relative path | `sqlite:///shop.db` | none (standard library) |
| SQLite, absolute path | `sqlite:////home/me/data/shop.db` | none |
| SQLite, in memory | `sqlite://` | none |
| PostgreSQL | `postgresql+psycopg2://user:pw@localhost:5432/shop` | `psycopg2-binary` |
| MySQL | `mysql+pymysql://user:pw@localhost:3306/shop` | `pymysql` |
SQLite paths trip people up because of the slash count. The first two slashes after sqlite: belong to the URL syntax (// with an empty host). The third slash starts the path. A relative path therefore takes three slashes, and an absolute Unix path takes four.
The engine is lazy
create_engine does not connect to anything. It records the URL and prepares a connection pool. The first real connection happens when something needs one. A wrong password or host therefore surfaces at the first query, not at create_engine. To test a connection on purpose, run a trivial statement:
from sqlalchemy import create_engine, inspect, text
engine = create_engine("sqlite:///shop.db")
with engine.connect() as connection:
print(connection.execute(text("SELECT 1")).scalar())
print(inspect(engine).get_table_names())The output is:
1
['orders']inspect(engine).get_table_names() lists the tables, which makes it a quick way to check that you reached the database you meant to reach.
Building URLs without exposing secrets
Do not paste passwords into source code. Read them from the environment. If a password contains characters such as @ or /, hand-built URL strings break, so use URL.create, which escapes each part correctly:
import os
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.engine import URL
url = URL.create(
"postgresql+psycopg2",
username=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
host=os.environ.get("DB_HOST", "localhost"),
port=5432,
database="shop",
)
engine = create_engine(url)
df = pd.read_sql_query("SELECT * FROM orders LIMIT 5", engine)
print(df)This example needs a running PostgreSQL server, the psycopg2-binary package, and the three environment variables. The same code works with another database if you change the dialect name and port.
Passing an engine, a connection, or a URL
You have three ways to hand SQLAlchemy to pandas. They differ in how connection lifetime is managed.
Pass the engine directly. pandas borrows a connection from the pool for the duration of the call and returns it afterwards. This is the simplest option and the right default for one-off reads.
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("sqlite:///shop.db")
df = pd.read_sql_query("SELECT id, customer, total FROM orders", engine)
print(df)Pass an explicit connection. Use this when several reads should share one connection, or when you want them to see a consistent view of the data. In SQLAlchemy 2.0, the first statement on a connection starts a transaction automatically. Closing the connection without calling commit() rolls the transaction back. That is harmless for reads, and it means you must commit yourself if you write.
import pandas as pd
from sqlalchemy import create_engine, text
engine = create_engine("sqlite:///shop.db")
with engine.connect() as connection:
ada = pd.read_sql_query(
text("SELECT * FROM orders WHERE customer = :name"),
connection,
params={"name": "Ada"},
)
totals = pd.read_sql_query(
"SELECT customer, SUM(total) AS revenue FROM orders GROUP BY customer",
connection,
)
print(ada)
print(totals)The first query wraps its SQL in text() so it can use the named placeholder :name. SQLAlchemy translates that placeholder into whatever style the underlying driver needs. The second query is a plain string with no parameters, which pandas accepts directly.
Pass a URL string. pandas calls create_engine for you. This is convenient in a notebook cell but creates a new engine, and therefore a new pool, on every call. If you read more than once, build one engine and reuse it.
import pandas as pd
df = pd.read_sql_query("SELECT * FROM orders", "sqlite:///shop.db")
print(df.shape)Choosing between sqlite3 and SQLAlchemy
| Question | sqlite3 connection | SQLAlchemy engine |
|---|---|---|
| Extra install needed | No | Yes |
| Databases supported | SQLite only | Many |
| `read_sql_table` available | No | Yes |
| Placeholder style | `?` (driver specific) | `:name` through `text()`, portable |
| Connection pooling | No | Yes |
| Best for | Scripts, tests, quick analysis of a local file | Anything that may move to another database, or needs table reads |
If you only ever read a local SQLite file, sqlite3 is enough. If your code might later point at a server database, start with SQLAlchemy. The read_sql_query calls stay the same, and only the engine URL changes.
Connection problems and what they mean
Most connection mistakes produce one of the following messages.
| Symptom | Cause | Fix |
|---|---|---|
| `UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested.` | You passed a raw connection from a driver such as `psycopg2` or `pymysql` | Wrap the database in a SQLAlchemy engine and pass that |
| `sqlalchemy.exc.ArgumentError: Could not parse SQLAlchemy URL from string 'shop.db'` | You passed a file path where pandas expected a URL | Use `"sqlite:///shop.db"`, or open the file with `sqlite3.connect` |
| `ImportError: Using URI string without sqlalchemy installed.` | You passed a URL string but SQLAlchemy is not installed | `pip install sqlalchemy` |
| `sqlite3.ProgrammingError: Cannot operate on a closed database.` | You used the connection after `close()`, often after a `closing` block | Do the reads inside the block, or open a new connection |
| `NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres` | Wrong dialect name, here `postgres` instead of `postgresql` | Fix the URL prefix |
| `ModuleNotFoundError: No module named 'psycopg2'` | The driver named in the URL is not installed | Install the driver package |
| `pandas.errors.DatabaseError: ... no such table` | You connected to a different file than you intended | Check the path and the working directory |
A reusable pattern
Put connection setup in one function, so the rest of your code does not care which kind of connection it receives:
import pandas as pd
from sqlalchemy import create_engine
def make_engine(url: str = "sqlite:///shop.db"):
return create_engine(url)
def revenue_by_customer(engine) -> pd.DataFrame:
return pd.read_sql_query(
"SELECT customer, SUM(total) AS revenue FROM orders GROUP BY customer",
engine,
)
engine = make_engine()
try:
print(revenue_by_customer(engine))
finally:
engine.dispose()The reading function takes the connection as an argument. A test can pass an in-memory engine instead of the production URL, and nothing else changes.
Exercises
Exercise
You run with sqlite3.connect("shop.db") as conn: and read a DataFrame inside the block. After the block, a colleague says the file is still locked on Windows. Why, and what is the fix?
Show answer
The with block on a sqlite3 connection only commits or rolls back the transaction. It does not close the connection, so the file stays open. Wrap the connection in contextlib.closing(...), or call conn.close() in a finally block.
Exercise
A script calls pd.read_sql_query("SELECT * FROM orders", "shop.db") and fails with ArgumentError: Could not parse SQLAlchemy URL. Give two corrected versions of the call.
Show answer
pandas treats a string con as a SQLAlchemy URL, and "shop.db" is a file path. Either use a URL: pd.read_sql_query("SELECT * FROM orders", "sqlite:///shop.db"). Or open the file with the standard library and pass the connection: conn = sqlite3.connect("shop.db") followed by pd.read_sql_query("SELECT * FROM orders", conn).
Exercise
create_engine("postgresql+psycopg2://user:wrongpw@localhost/shop") runs without any error. Why does it not fail, and where will the error appear?
Show answer
create_engine is lazy. It stores the URL and builds a pool but opens no connection. The authentication error appears at the first operation that needs a connection, such as engine.connect() or a pandas read call that uses the engine.