API Reference

psycopg

Modern PostgreSQL adapter for Python with both sync and async APIs, connection pooling and server cursors.

Official Documentation ↗
CompatibilityThis documentation covers version psycopg 3.2+ / PostgreSQL 12+ / Python 3.9+. Check the official docs for the latest API surface.

Installation

pippip install psycopg

Methods

Overview

psycopg is the modern PostgreSQL adapter for Python, supporting synchronous and asyncio usage, connection pooling and efficient parameter binding.

Core Methods

connect opens a connection, cursor executes statements with parameters and fetches results, and the pool module provides bounded connection reuse. Context managers ensure cleanup.

Usage Notes

Use parameter markers instead of string formatting, commit or roll back explicitly, and pool connections in services. Prefer server-side cursors for large result sets.

Common Pitfalls

Building SQL by concatenation invites injection. Not committing leaves changes invisible. Leaking connections from a pool stalls the application and can exhaust db limits.

FAQ

What changed from psycopg2?
psycopg 3 supports both sync and async, uses a new server-side binding model, and has a cleaner API while keeping much of the same usage. psycopg2 remains for legacy code.
How do I prevent SQL injection?
Always pass parameters to execute separately rather than formatting values into the SQL string. The adapter handles quoting and type adaptation safely.
When should I use a pool?
Use a pool in servers and long-running processes to reuse connections and bound concurrency. Opening a connection per request adds latency and can exhaust database connection limits.