The most widely used PostgreSQL adapter for Python. Sync only. Two packages on PyPI: psycopg2 (source, requires libpq dev headers) and psycopg2-binary (pre-compiled, no system deps). Official docs explicitly warn against psycopg2-binary in production. Current version: 2.9.11 (Mar 2026). For async PostgreSQL use asyncpg or psycopg (v3). For new projects consider migrating to psycopg (v3) which has both sync and async.
pip install psycopg2-binaryVerified import paths — ran on the pinned version, not inferred.
Minimal psycopg2 connection with RealDictCursor and parameterized query.
Use psycopg2-binary for development. In production use psycopg2 with system libpq: apt-get install libpq-dev && pip install psycopg2
Always: cur.execute('SELECT * FROM t WHERE id = %s', (value,)) — note the trailing comma to make a tuple.Always wrap single values in a tuple: (value,) not value.
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
For async: pip install asyncpg or pip install psycopg[binary] (psycopg v3)
psycopg2: 'import psycopg2'. psycopg v3: 'import psycopg'. Do not mix them.
Use psycopg2.pool.ThreadedConnectionPool or let SQLAlchemy manage the pool.