psycopg-binary

3.3.3 · active · verified Sun Mar 29

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.

Warnings

Install

Imports

Quickstart

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.

view raw JSON →