Skip to main content
Albero Academy

PostgreSQL

Connect to a production-grade database with psycopg.

Databases9 min

When you outgrow SQLite, PostgreSQL is the go-to open-source database for production — robust, feature-rich, and battle-tested. The Python code looks almost identical; you swap the driver and connect to a running server instead of a file.

Connecting with psycopg

psycopg (v3) is the standard driver. The same connection → cursor → execute pattern applies:

psycopg
import psycopg
with psycopg.connect("postgresql://user:pass@localhost/albero") as conn:
with conn.cursor() as cur:
cur.execute("SELECT name FROM students WHERE package > %s", (7,))
rows = cur.fetchall() # all matching rows
# cur.fetchone() for a single row

Connection pooling

Opening a database connection is expensive. In a server handling many requests, use a connection pool (e.g. psycopg's pool, or via SQLAlchemy) to reuse connections instead of opening one per request.

Key takeaways

  1. 01PostgreSQL is the standard robust production database.
  2. 02psycopg is the standard Python driver; the connect→cursor→execute pattern is the same as SQLite.
  3. 03Its placeholder is %s (parameterise, never interpolate).
  4. 04Keep credentials in environment variables, not in code.
  5. 05Use a connection pool in servers to avoid opening a connection per request.

Finished this chapter?

Mark it complete to track your progress through Python.