psycopg2
Most widely-used PostgreSQL adapter for Python. psycopg2 is a C extension providing fast, full-featured PostgreSQL access with thread safety, server-side cursors, COPY support, and NOTIFY/LISTEN for pub/sub. psycopg3 (new) adds async/await support and type annotations. Used by Django, SQLAlchemy, and most Python PostgreSQL applications. The de facto standard for raw PostgreSQL access in Python.
Score Breakdown
⚙ Agent Friendliness
🔒 Security
Parameterized queries prevent SQL injection. TLS connections via sslmode parameter. Connection credentials must be in environment variables. Never use string formatting for query construction.
⚡ Reliability
Best When
You need direct PostgreSQL access in Python with maximum compatibility, or you're using it as the driver under SQLAlchemy/Django.
Avoid When
You need async PostgreSQL access — use asyncpg for async-native high performance.
Use Cases
- • Connect Python applications to PostgreSQL databases with full protocol support including server-side cursors
- • Execute parameterized SQL queries safely without SQL injection risk
- • Use COPY FROM/TO for high-throughput bulk data loading into PostgreSQL tables
- • Implement PostgreSQL LISTEN/NOTIFY for real-time event notifications from the database
- • Use as the low-level driver under SQLAlchemy, Django ORM, or asyncpg for PostgreSQL connections
Not For
- • Non-PostgreSQL databases — use pymysql for MySQL, sqlite3 for SQLite
- • Async applications with Tokio-style concurrency — use asyncpg or psycopg3 for async PostgreSQL
- • ORM-based development — psycopg2 is a driver; use SQLAlchemy or Django ORM on top
Interface
Authentication
PostgreSQL credentials (user, password, host, dbname) in connection string. SSL certificates for TLS connections.
Pricing
Free and open source.
Agent Metadata
Known Gotchas
- ⚠ psycopg2 uses %s as query placeholder regardless of database — NOT ? (SQLite style) or $1 (asyncpg style); mixing placeholder styles causes syntax errors
- ⚠ conn.cursor() creates a cursor but does NOT execute queries — always call cursor.execute(sql, params) with parameterized values, never string interpolation
- ⚠ Transactions are open by default — every connection starts in a transaction; call conn.commit() to persist or conn.rollback() to abort; forgetting commit means data isn't persisted
- ⚠ psycopg2 connection objects are NOT thread-safe — use a connection pool (psycopg2.pool.ThreadedConnectionPool) for multi-threaded applications
- ⚠ psycopg2 requires libpq C library to be installed — in Docker and CI environments, install libpq-dev (apt) or postgresql-libs (apk) before pip install psycopg2
- ⚠ psycopg3 (psycopg) is the successor to psycopg2 with different import name — install with pip install psycopg[c]; import as import psycopg, not psycopg2
Full Evaluation Report
Detailed scoring breakdown, competitive positioning, security analysis, and improvement recommendations for psycopg2.
Scores are editorial opinions as of 2026-03-06.