psycopg2-pool provides robust connection pooling for the psycopg2 PostgreSQL adapter. It helps manage a fixed number of database connections, improving performance by reusing existing connections and reducing the overhead of establishing new ones. It currently stands at version 1.2 and is a stable library with a low release cadence.
pip install psycopg2-poolVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to initialize a `ConnectionPool`, obtain connections using both `with` statements (recommended) and explicit `getconn`/`putconn` calls, execute a simple query, and properly close the pool upon application shutdown. Ensure your PostgreSQL server is running and database credentials are set, ideally via environment variables.
Use the `with` statement: `with pool.getconn() as conn: ...` or wrap explicit `getconn` in a `try...finally` block: `conn = pool.getconn(); try: ... finally: pool.putconn(conn)`.
Ensure `pool.close()` is called during application shutdown, for example, in a `finally` block or a signal handler.
Choose either `psycopg2` or `psycopg2-binary` and stick to one in your project's dependencies. If unsure, `psycopg2-binary` is often easier for local development, while `psycopg2` is preferred for production builds where you control system dependencies.
Ensure that entire transactions are handled within the scope of a single connection obtained from the pool. Do not assume transactional context will persist across multiple `getconn()` calls, even if they appear consecutive.
Ensure all connections obtained with `pool.getconn()` are returned to the pool using `pool.putconn(conn)` (preferably via a `with` statement for automatic handling) or increase `maxconn` if your workload truly requires more concurrent connections.
Verify that `pool.getconn()` successfully returned a connection before trying to use it. If explicitly managing connections, ensure you're not using a reference to a connection after `pool.putconn()` has been called on it.
First, ensure `psycopg2-pool` is installed: `pip install psycopg2-pool`. Then, correct your import statement to `from psycopg2_pool import ConnectionPool`.