Databases · Intermediate · 24 min
Connect to PostgreSQL from Python with psycopg 3
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7 · Python 3.15 · psycopg 3.3 · uv 0.13
You will connect a Python 3.15 project to PostgreSQL 18 with psycopg 3.3, run parameterised queries, shape rows as dicts and dataclasses, group writes in transactions, load 100,000 rows with COPY, stream large results, share connections with a pool and handle errors by SQLSTATE.
On this page
ORMs such as SQLAlchemy and SQLModel are built on a driver: the library that opens the connection, sends SQL and turns rows into Python values. For PostgreSQL that driver is usually psycopg. Knowing it directly pays off when an ORM gets in the way, when you write a script that loads a file, or when you need to see what your ORM is doing.
In this tutorial you build a small project for a fictional prepaid electricity vendor that records meter top-ups. You connect with a connection string from the environment, see an f-string turn into an SQL injection, choose how rows come back, make writes all-or-nothing, load 100,000 rows two ways and time them, read them back without holding them all in memory, run queries from several threads through a pool, and catch errors by their SQLSTATE code.
The commands use psycopg 3.3, Python 3.15 and PostgreSQL 18. PostgreSQL 19 came out in November 2026, and the code here should work the same on it. psycopg 3 is a different package from the older psycopg2: it is imported as psycopg, and its API differs in places.
Step 1 · Create a role, a database and a project
Give the application its own login role instead of using the postgres superuser. Create a role called shopapp; --pwprompt asks for its password twice, so the password never appears in your shell history:
sudo -u postgres createuser --pwprompt shopappCreate a database owned by that role, so it can create tables in it:
sudo -u postgres createdb --owner=shopapp shopYour code needs to know where the database is, but the password does not belong in the code, in a committed file or in an environment variable that other processes can read. libpq, the C library psycopg uses, reads passwords from ~/.pgpass. Create the file with private permissions if you do not have one yet. The first command leaves an existing file and its lines alone; the second makes sure only you can read it:
[ -e ~/.pgpass ] || install -m 600 /dev/null ~/.pgpass
chmod 600 ~/.pgpass
ls -l ~/.pgpassls -l shows -rw------- at the start of the line. Open the file in an editor, for example with nano ~/.pgpass, and add one line in the form host:port:database:user:password. Replace the last field with the password you typed for shopapp:
localhost:5432:shop:shopapp:the-password-you-choseNow put the rest of the connection details in an environment variable. The connection string has no password in it; libpq finds the matching line in ~/.pgpass:
export DATABASE_URL="postgresql://shopapp@localhost:5432/shop"
psql "$DATABASE_URL" -c "SELECT current_user, current_database();"The variable lasts until you close the terminal. To keep it, add the export line to ~/.bashrc, or use a tool such as direnv for a per-project setting. On a deployed app, the platform's settings for environment variables or secrets do the same job.
Next, create the project and add psycopg. The binary extra installs a build that bundles libpq, so nothing else needs to be installed on the machine. The version ranges allow patch releases of 3.3 and nothing newer:
mkdir -p ~/psycopg-demo
cd ~/psycopg-demo
uv init --no-package --python 3.15
uv add "psycopg[binary]>=3.3,<3.4" "psycopg-pool>=3.3,<3.4"Check it worked
The psql command printed a one-row table with shopapp and shop. If it asked for a password, the ~/.pgpass line does not match the host, port, database and user exactly, or the file is readable by others (libpq ignores it then). Now check the Python side:
uv run python -c "import psycopg, importlib.metadata as m; print(psycopg.__version__, m.version('psycopg-pool'), psycopg.pq.__impl__)"It prints something like 3.3.9 3.3.3 binary. The last word says which implementation psycopg loaded: binary is the bundled build.
Step 2 · Connect and pass values as parameters
Write a script that reads the connection string and prints who it connected as. It stops with a clear message if the variable is missing, instead of a KeyError:
cat > connect.py <<'PY'
import os
import sys
import psycopg
conninfo = os.environ.get("DATABASE_URL")
if not conninfo:
sys.exit("Set DATABASE_URL first")
with psycopg.connect(conninfo) as conn:
user, db = conn.execute("SELECT current_user, current_database()").fetchone()
print(f"connected as {user} to {db}")
print("server version:", conn.info.server_version)
PY
uv run connect.pyconn.execute creates a cursor, runs the statement and returns the cursor, so you can call fetchone() on the result directly. conn.info.server_version is a number such as 180007 for 18.7.
Now create the table and add four top-ups. Every value goes into the query as a %s placeholder, and the values travel as a separate tuple:
cat > add.py <<'PY'
import os
from decimal import Decimal
import psycopg
TOPUPS = [
("TX-1001", "45010000001", Decimal("2500.00")),
("TX-1002", "45010000002", Decimal("1000.00")),
("TX-1003", "45010000001", Decimal("5000.00")),
("TX-1004", "45010000003", Decimal("1500.00")),
]
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS topups (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
reference text NOT NULL UNIQUE,
meter text NOT NULL,
amount numeric(10, 2) NOT NULL CHECK (amount > 0),
bought_at timestamptz NOT NULL DEFAULT now()
)
""")
for reference, meter, amount in TOPUPS:
conn.execute(
"INSERT INTO topups (reference, meter, amount) VALUES (%s, %s, %s)"
" ON CONFLICT (reference) DO NOTHING",
(reference, meter, amount),
)
count = conn.execute("SELECT count(*) FROM topups").fetchone()[0]
print("rows:", count)
PY
uv run add.pyAmounts are Decimal, not float. A float cannot hold most decimal fractions exactly, and money must add up to the cent. psycopg sends a Decimal as numeric and reads numeric back as Decimal. ON CONFLICT ... DO NOTHING makes the script safe to run twice.
To see why placeholders matter, write a lookup that runs the same query two ways: once with the input pasted in by an f-string, once as a parameter:
cat > lookup.py <<'PY'
import os
import sys
import psycopg
meter = sys.argv[1]
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
# Never do this: the input becomes part of the SQL text.
unsafe = conn.execute(f"SELECT count(*) FROM topups WHERE meter = '{meter}'").fetchone()[0]
# Do this: the input is sent as a value, apart from the SQL.
safe = conn.execute("SELECT count(*) FROM topups WHERE meter = %s", (meter,)).fetchone()[0]
print("f-string: ", unsafe)
print("parameter:", safe)
PY
uv run lookup.py 45010000001
uv run lookup.py "x' OR '1'='1"With the second input, the f-string builds WHERE meter = 'x' OR '1'='1', which is true for every row. The parameter version looks for a meter literally called x' OR '1'='1 and finds none. psycopg 3 sends the query and the values to the server separately, so a value can never change the shape of the statement.
Three rules follow. Use %s for every value, whatever its type, and never put quotes around it. Pass a tuple or list even for one value: (meter,) with the trailing comma. Placeholders work for values only; for a table or column name chosen at runtime, build the query with psycopg.sql.Identifier.
Check it worked
connect.py printed connected as shopapp to shop, and add.py printed rows: 4. The first lookup printed 2 twice. The second printed f-string: 4 and parameter: 0: the f-string leaked every row.
Step 3 · Get rows as dicts and dataclasses
By default each row is a tuple, so you read columns by position. A row factory changes the shape. dict_row gives dictionaries keyed by column name, and class_row builds an object of any class whose fields match the column names, such as a dataclass:
cat > rows.py <<'PY'
import os
from dataclasses import dataclass
from decimal import Decimal
import psycopg
from psycopg.rows import class_row, dict_row
@dataclass
class Topup:
reference: str
meter: str
amount: Decimal
with psycopg.connect(os.environ["DATABASE_URL"], row_factory=dict_row) as conn:
first = conn.execute(
"SELECT reference, meter, amount FROM topups ORDER BY reference LIMIT 1"
).fetchone()
print(first)
with conn.cursor(row_factory=class_row(Topup)) as cur:
cur.execute(
"SELECT reference, meter, amount FROM topups WHERE meter = %s ORDER BY reference",
("45010000001",),
)
topups = cur.fetchall()
for topup in topups:
print(topup)
print("total:", sum(t.amount for t in topups))
PY
uv run rows.pyThe row factory set on the connection applies to every cursor it opens. The one passed to conn.cursor() overrides it for that cursor only. class_row calls the class with the columns as keyword arguments. If a column has no matching field, or a required field (one without a default) has no column, it raises an error, so select the columns the class declares. Use AS to rename a column when the names differ.
Check it worked
The output is:
{'reference': 'TX-1001', 'meter': '45010000001', 'amount': Decimal('2500.00')}
Topup(reference='TX-1001', meter='45010000001', amount=Decimal('2500.00'))
Topup(reference='TX-1003', meter='45010000001', amount=Decimal('5000.00'))
total: 7500.00Step 4 · Group writes in a transaction
psycopg starts a transaction with the first statement you run on a connection, and nothing is saved until it is committed. The with psycopg.connect(...) as conn: block you have used so far commits when the block ends normally and rolls back if an exception escapes it. A connection you open without with and close without conn.commit() loses its work.
For a group of writes that must succeed or fail together, wrap them in conn.transaction(). This script tries to save a batch of two top-ups where the second reuses an existing reference, then shows what happens when you forget to commit:
cat > batch.py <<'PY'
import os
from decimal import Decimal
import psycopg
URL = os.environ["DATABASE_URL"]
INSERT = "INSERT INTO topups (reference, meter, amount) VALUES (%s, %s, %s)"
batch = [
("TX-2001", "45010000002", Decimal("800.00")),
("TX-1001", "45010000004", Decimal("300.00")), # duplicate reference
]
with psycopg.connect(URL) as conn:
before = conn.execute("SELECT count(*) FROM topups").fetchone()[0]
try:
with conn.transaction():
for row in batch:
conn.execute(INSERT, row)
except psycopg.errors.UniqueViolation as err:
print("batch rejected by", err.diag.constraint_name)
after = conn.execute("SELECT count(*) FROM topups").fetchone()[0]
print("before:", before, "after:", after)
# No with block and no commit: the insert is thrown away on close.
conn = psycopg.connect(URL)
conn.execute(INSERT, ("TX-3001", "45010000002", Decimal("200.00")))
conn.close()
with psycopg.connect(URL) as conn:
found = conn.execute("SELECT count(*) FROM topups WHERE reference = %s", ("TX-3001",)).fetchone()[0]
print("TX-3001 saved:", found == 1)
PY
uv run batch.pyTX-2001 was inserted, then the duplicate failed, and conn.transaction() rolled back both. Because the outer with block had already started a transaction, conn.transaction() used a savepoint, so the connection stayed usable for the count that follows. err.diag holds the details the server sent, including the constraint that failed.
If you prefer each statement to be saved at once, connect with psycopg.connect(URL, autocommit=True) and use conn.transaction() only around the groups that must be atomic.
Check it worked
The output is:
batch rejected by topups_reference_key
before: 4 after: 4
TX-3001 saved: FalseStep 5 · Load 100,000 rows with executemany and COPY
Bulk loads come up all the time: a day of sales from a payment provider, a CSV export from a partner. Compare two ways to load 100,000 rows into a staging table. executemany runs one INSERT per row, sent in batches. COPY streams the rows to the server in PostgreSQL's own bulk format:
cat > load.py <<'PY'
import os
import time
from decimal import Decimal
import psycopg
N = 100_000
rows = [(f"45{n:09d}", Decimal((n % 50 + 1) * 100)) for n in range(N)]
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS topups_import (
meter text NOT NULL,
amount numeric(10, 2) NOT NULL
)
""")
conn.execute("TRUNCATE topups_import")
start = time.perf_counter()
with conn.cursor() as cur:
cur.executemany("INSERT INTO topups_import (meter, amount) VALUES (%s, %s)", rows)
many_seconds = time.perf_counter() - start
many_count = conn.execute("SELECT count(*) FROM topups_import").fetchone()[0]
conn.execute("TRUNCATE topups_import")
start = time.perf_counter()
with conn.cursor() as cur:
with cur.copy("COPY topups_import (meter, amount) FROM STDIN") as copy:
for row in rows:
copy.write_row(row)
copy_seconds = time.perf_counter() - start
copy_count = conn.execute("SELECT count(*) FROM topups_import").fetchone()[0]
print(f"executemany: {many_count} rows in {many_seconds:.2f} s")
print(f"COPY: {copy_count} rows in {copy_seconds:.2f} s")
PY
uv run load.pyThe data is made up: 100,000 meter numbers with amounts from 100 to 5,000 in steps of 100. Both loads run in one transaction, and the TRUNCATE between them empties the table, so the table ends with the 100,000 rows from COPY.
write_row adapts each Python value the same way query parameters are adapted, so there is no CSV quoting to get wrong. To load an existing CSV file instead, read it in chunks and pass them to copy.write() with COPY ... FROM STDIN (FORMAT csv, HEADER). Server-side COPY ... FROM '/path/file.csv' reads a file on the database server, needs extra privileges, and is covered in /tutorials/load-and-export-csv-data-with-postgresql-copy.
Fewer round trips matter most on a slow link. If your database is in a cloud region far from where the loader runs, or the loader runs over a mobile or prepaid data connection, COPY saves both time and data.
Check it worked
Both lines report 100000 rows. The times depend on your machine and network, but COPY is typically several times faster than executemany, and the gap grows with the distance to the server.
Step 6 · Read a large result with a server-side cursor
An ordinary cursor fetches the whole result into your program's memory when the query runs. For 100,000 short rows that is fine. For tens of millions, or on a small virtual server with 1 GB of RAM, it is not. A named cursor is a server-side cursor: PostgreSQL keeps the result and psycopg fetches it in batches of itersize rows (100 by default) as you loop:
cat > stream.py <<'PY'
import os
from decimal import Decimal
import psycopg
rows = 0
total = Decimal(0)
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
with conn.cursor(name="all_imports") as cur:
cur.itersize = 5000
cur.execute("SELECT meter, amount FROM topups_import")
for meter, amount in cur:
rows += 1
total += amount
print(f"rows={rows} total={total}")
PY
uv run stream.pyPassing name= is what makes the cursor server-side. A larger itersize means fewer round trips and more memory per batch; a few thousand is a sensible start. A server-side cursor lives inside a transaction, which the with block gives you. On an autocommit=True connection, create it with withhold=True so it survives outside a transaction.
Check it worked
The output is rows=100000 total=255000000.00. Each of the 50 amounts appears 2,000 times, and 2,000 × (100 + 200 + … + 5,000) is 255,000,000.
Step 7 · Share connections with a pool
Opening a PostgreSQL connection means a new server process, authentication and several round trips. That costs a few milliseconds on the same machine and more over a network, especially with TLS and SCRAM authentication. A web app or worker that opens one per request wastes that time and can exhaust the server's max_connections. A pool opens a few connections and lends them out.
This script runs eight queries from eight threads through a pool that holds at most four connections. Each query sleeps for 0.2 seconds so that they overlap, and reports the server process ID that served it:
cat > pool.py <<'PY'
import os
from concurrent.futures import ThreadPoolExecutor
from psycopg_pool import ConnectionPool
def backend_pid(pool):
with pool.connection() as conn:
return conn.execute("SELECT pg_backend_pid() FROM pg_sleep(0.2)").fetchone()[0]
with ConnectionPool(os.environ["DATABASE_URL"], min_size=2, max_size=4, open=True) as pool:
pool.wait()
with ThreadPoolExecutor(max_workers=8) as executor:
pids = list(executor.map(lambda _: backend_pid(pool), range(8)))
print("queries:", len(pids))
print("connections used:", len(set(pids)))
print("at most 4:", len(set(pids)) <= 4)
PY
uv run pool.pypool.wait() blocks until the first min_size connections are ready. pool.connection() lends a connection for the length of the with block; when the block ends, the pool commits any open transaction (or rolls it back after an exception) and takes the connection back. Threads that ask while all four are busy wait in a queue.
In an app, create one pool when the process starts and close it when it stops. A FastAPI lifespan handler or a module-level pool both work. Keep max_size times the number of app processes below the server's max_connections.
Check it worked
The output shows queries: 8, a number of connections between 2 and 4, and at most 4: True.
Step 8 · Catch errors by SQLSTATE
Every error the server reports carries a five-character SQLSTATE code, and the first two characters give its class. psycopg maps each code to an exception class in psycopg.errors, all under psycopg.Error. The classes you will meet most often:
23integrity constraint violation: bad data, such as23505(unique) and23514(check). Tell the user; retrying will not help.40transaction rollback, such as40001(serialisation failure) and40P01(deadlock). Retry the whole transaction.08connection exception. A connection that never reaches the server raisespsycopg.OperationalErrorwith no SQLSTATE at all, because the server never answered.
cat > errors.py <<'PY'
import os
from decimal import Decimal
import psycopg
from psycopg import errors
URL = os.environ["DATABASE_URL"]
INSERT = "INSERT INTO topups (reference, meter, amount) VALUES (%s, %s, %s)"
def save(values, url=URL):
try:
with psycopg.connect(url, connect_timeout=5) as conn:
conn.execute(INSERT, values)
return "saved"
except errors.UniqueViolation:
return "duplicate reference, already recorded"
except psycopg.Error as err:
if err.sqlstate and err.sqlstate.startswith("23"):
return f"bad data: {err.sqlstate} {type(err).__name__}"
if err.sqlstate is None:
return f"cannot reach the database: {type(err).__name__}"
raise
print(save(("TX-1001", "45010000001", Decimal("2500.00"))))
print(save(("TX-5001", "45010000001", Decimal("-50.00"))))
print(save(("TX-5002", "45010000001", Decimal("50.00")), url="postgresql://shopapp@localhost:1/shop"))
print(errors.lookup("23505").__name__)
PY
uv run errors.pyThe first call reuses a reference, the second sends a negative amount that the CHECK constraint rejects, and the third points at port 1, where nothing listens. Catch the specific class first and the general psycopg.Error last, and re-raise anything you do not know how to handle rather than hiding it. errors.lookup turns a code from the PostgreSQL error list into its class, which helps when you read a code in a log.
Check it worked
The output is:
duplicate reference, already recorded
bad data: 23514 CheckViolation
cannot reach the database: OperationalError
UniqueViolationStep 9 · Clean up
This deletes the demo project, the shop database with every row in it, and the shopapp role. Leave your shell's current folder first:
cd ~
rm -rf ~/psycopg-demo
sudo -u postgres dropdb shop
sudo -u postgres dropuser shopapp
unset DATABASE_URLOpen ~/.pgpass in your editor and delete the localhost:5432:shop:shopapp:... line. If it was the only line, delete the file with rm ~/.pgpass. If you added the export DATABASE_URL=... line to ~/.bashrc, delete that line too.
Check it worked
sudo -u postgres psql -X -Atc "SELECT count(*) FROM pg_database WHERE datname = 'shop';" -c "SELECT count(*) FROM pg_roles WHERE rolname = 'shopapp';"Both lines print 0.
Next steps
- See the injection from this tutorial in more forms, and the fixes in Node.js too: /tutorials/prevent-sql-injection-in-python-and-node.
- Put a typed model layer on top of the database in a web API: /tutorials/connect-fastapi-to-a-database-with-sqlmodel.
- The psycopg documentation at psycopg.org/psycopg3/docs covers async connections, pipeline mode, type adaptation and
psycopg.sqlfor building dynamic queries.
Related tutorials
- Understand PostgreSQL transactions and isolation levelsYou will race two psql sessions against each other in PostgreSQL 18 to cause a lost update, a non-repeatable read, write skew and a deadlock, then fix each one with row locks, the right isolation level, a retry loop, savepoints and lock timeouts.
- Summarise data in SQL with GROUP BY, HAVING and aggregatesYou will turn twelve order rows into a PostgreSQL 18 revenue report by month and region, with subtotals, saved as a view and a CSV file that matches a hand check.
- Store and query JSON in PostgreSQL with JSONBYou will store payment webhook payloads in a PostgreSQL 18 jsonb column, query them with operators, SQL/JSON paths and JSON_TABLE, update keys in place, prove two indexes with EXPLAIN and guard the data with a CHECK constraint.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials