psycopg-binary

raw JSON →
3.3.3 verified Tue May 12 auth: no python install: verified quickstart: verified

psycopg-binary is the pre-compiled binary distribution for Psycopg 3, a modern PostgreSQL database adapter for Python. It provides C optimizations for performance without requiring local build prerequisites. While `psycopg-binary` is the package name on PyPI, it acts as an optional component for the core `psycopg` library (Psycopg 3). It is actively maintained, currently at version 3.3.3, and follows a frequent release cadence, often aligning with new Python and PostgreSQL versions.

pip install "psycopg[binary,pool]"
error ERROR: Could not find a version that satisfies the requirement psycopg-binary (from versions: none)
cause This error typically occurs when `pip` cannot find a pre-compiled wheel for `psycopg-binary` that matches your Python version, operating system, and architecture, often seen on newer or less common platforms like certain ARM-based Macs or specific Linux distributions where wheels might not be available yet.
fix
Try installing psycopg (the source distribution) which requires PostgreSQL development headers and a C compiler, or use a Python version/platform combination for which pre-built psycopg-binary wheels exist. For macOS M1/M2, ensure you have the latest pip and try installing psycopg if psycopg-binary fails. You might also need to install PostgreSQL via Homebrew (brew install postgresql) and its development libraries.
error ModuleNotFoundError: No module named 'psycopg2'
cause This error happens when you have installed `psycopg-binary` (Psycopg 3) but are attempting to import the module using the old `psycopg2` name, or `psycopg2` itself is not installed. Psycopg 3 uses `import psycopg`.
fix
If you intended to use Psycopg 3, change your import statement from import psycopg2 to import psycopg. If you genuinely need psycopg2, you must install it separately via pip install psycopg2-binary.
error psycopg.OperationalError: could not connect to server: Connection refused
cause This is a runtime error indicating that the Python application could not establish a connection with the PostgreSQL database server. Common reasons include the PostgreSQL server not running, incorrect host or port in the connection string, firewall blocking the connection, or incorrect database credentials.
fix
Verify that the PostgreSQL server is running and accessible from the machine running your Python application. Double-check the host, port, dbname, user, and password in your psycopg.connect() call. Ensure no firewall rules are blocking the connection on either the client or server side.
error AttributeError: 'Connection' object has no attribute 'mogrify'
cause `mogrify` is a method available on `psycopg.ClientCursor` objects, not directly on the `Connection` object, in Psycopg 3. You need to create a `ClientCursor` to use this method.
fix
When creating your cursor, specify cursor_factory=psycopg.ClientCursor to obtain a client-side cursor that supports the mogrify method.
import psycopg

conn = psycopg.connect(dbname='your_db', user='your_user', password='your_password', host='your_host', cursor_factory=psycopg.ClientCursor)
cur = conn.cursor()
query = "SELECT * FROM users WHERE id = %s"
mogrified_query = cur.mogrify(query, (1,))
print(mogrified_query)
breaking The `psycopg-binary` package provides C optimizations for Psycopg 3, but the primary library to import is `psycopg`. Do not `import psycopg_binary` directly. If migrating from `psycopg2-binary`, the installation command is `pip install "psycopg[binary]"` (or `"psycopg[binary,pool]"`), and the import path changes from `import psycopg2` to `import psycopg`.
fix Install using `pip install "psycopg[binary,pool]"` and always `import psycopg` in your code.
gotcha The `psycopg-binary` package bundles its own versions of C libraries like `libpq` and `libssl`. This can lead to conflicts with other Python modules or system libraries (potentially causing segfaults, especially with Python's `ssl` module under concurrency). System library upgrades will not update the versions used by `psycopg-binary`. For production environments, building from source (`pip install psycopg[c]`) is often advised to link against system libraries.
fix For production, consider installing `psycopg[c]` (which requires build tools and `libpq-dev`) or be aware of potential library conflicts. Test thoroughly in your target environment.
breaking Psycopg 3 introduces several API changes compared to Psycopg 2. Key differences include server-side parameter binding (which can break queries like `SET TimeZone`), a redesigned connection pool, and different handling of date/time infinities. Refer to the official 'Differences from psycopg2' documentation for a complete list of changes.
fix Review the official Psycopg 3 documentation for migration guides and adapt your code to the new API. Be especially careful with `SET` statements and date/time handling.
gotcha Psycopg 3.3.x officially supports Python versions from 3.10 to 3.14. Older Python versions (e.g., 3.8, 3.9, 3.7) are only supported by earlier Psycopg 3.x releases. Ensure your Python environment meets the requirements for the `psycopg-binary` version you are installing.
fix Always check the release notes for the specific `psycopg` (and thus `psycopg-binary`) version for compatible Python versions, and ensure your environment is up-to-date.
gotcha Older versions of `psycopg[binary]` (prior to 3.1.11) had reports of high memory consumption, particularly for large `SELECT` queries, due to query caching. This issue was addressed in `psycopg` version 3.1.11.
fix Ensure you are using `psycopg-binary` (via `psycopg[binary]`) version 3.1.11 or newer to benefit from memory usage improvements for large queries.
breaking The `psycopg` library failed to connect to the PostgreSQL database server because the server refused the connection. This typically indicates that the PostgreSQL server is not running, is not accessible from the client's network, or is not configured to accept TCP/IP connections on the specified host and port.
fix Ensure the PostgreSQL database server is running and accessible from the application's environment. Verify network connectivity, firewall rules, and that the server is configured to listen on the correct host and port (e.g., check `listen_addresses` in `postgresql.conf` and client authentication rules in `pg_hba.conf`).
breaking The database connection failed because the PostgreSQL server was not running or was not accessible at the specified host and port. This is an infrastructure issue, not directly related to the Psycopg library's installation or usage.
fix Ensure your PostgreSQL server is running and configured to accept connections on the specified host and port (e.g., '127.0.0.1', port 5432). Check server logs for startup errors and firewall rules.
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.37s 35.6M
3.10 alpine (musl) - - 0.46s 35.6M
3.10 slim (glibc) wheel 2.3s 0.26s 39M
3.10 slim (glibc) - - 0.25s 39M
3.11 alpine (musl) wheel - 0.58s 38.0M
3.11 alpine (musl) - - 0.80s 38.0M
3.11 slim (glibc) wheel 2.3s 0.50s 41M
3.11 slim (glibc) - - 0.50s 41M
3.12 alpine (musl) wheel - 0.70s 29.7M
3.12 alpine (musl) - - 0.79s 29.7M
3.12 slim (glibc) wheel 1.9s 0.67s 33M
3.12 slim (glibc) - - 0.69s 33M
3.13 alpine (musl) wheel - 0.69s 29.5M
3.13 alpine (musl) - - 0.74s 29.4M
3.13 slim (glibc) wheel 2.1s 0.66s 33M
3.13 slim (glibc) - - 0.73s 33M
3.9 alpine (musl) wheel - 0.34s 28.6M
3.9 alpine (musl) - - 0.35s 28.6M
3.9 slim (glibc) wheel 2.7s 0.29s 32M
3.9 slim (glibc) - - 0.31s 32M

This quickstart demonstrates how to establish a connection to a PostgreSQL database using Psycopg 3 (installed via `psycopg[binary]`), create a table, insert data, and query it. It uses environment variables for connection details for security and flexibility. The `with` statement ensures proper resource management.

import os
import psycopg

# Retrieve connection string from environment or use a default
conn_str = os.environ.get(
    "PSYCOPG_CONN_STRING",
    "dbname=test user=postgres password=mysecretpassword host=localhost port=5432"
)

try:
    # Establish a connection using a context manager for automatic closing
    with psycopg.connect(conn_str) as conn:
        # Open a cursor to perform database operations
        with conn.cursor() as cur:
            # Example: Create a table (if it doesn't exist)
            cur.execute("DROP TABLE IF EXISTS test_table")
            cur.execute("CREATE TABLE test_table (id SERIAL PRIMARY KEY, name VARCHAR(100))")

            # Example: Insert data
            cur.execute("INSERT INTO test_table (name) VALUES (%s)", ("Alice",))
            cur.execute("INSERT INTO test_table (name) VALUES (%s)", ("Bob",))

            # Commit the transaction (if not in autocommit mode, default is autocommit=False)
            conn.commit()

            # Example: Query data
            cur.execute("SELECT id, name FROM test_table ORDER BY id")
            print("--- Data from test_table ---")
            for record in cur:
                print(f"ID: {record[0]}, Name: {record[1]}")

except psycopg.Error as e:
    print(f"Database error: {e}")
    # In a production application, you would handle this more robustly,
    # e.g., logging the error and potentially exiting or retrying.