Psycopg C-optimized

3.3.3 · active · verified Sun Apr 12

Psycopg 3 is a modern PostgreSQL database adapter for Python, designed to leverage modern Python (asyncio, static typing) and PostgreSQL features (binary protocol, pipeline mode). `psycopg-c` is an optional component providing C-optimized speedups for the core `psycopg` library, offering performance benefits over the pure Python implementation. It is actively maintained with frequent updates, currently at version 3.3.3.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic synchronous connection to a PostgreSQL database, creating a table, inserting a record, and querying it using `psycopg.connect` and context managers for connection and cursor. It uses environment variables for connection parameters for security and flexibility.

import psycopg
import os

# Ensure environment variables are set for connection details
DB_HOST = os.environ.get('PG_HOST', 'localhost')
DB_PORT = os.environ.get('PG_PORT', '5432')
DB_NAME = os.environ.get('PG_DATABASE', 'testdb')
DB_USER = os.environ.get('PG_USER', 'user')
DB_PASSWORD = os.environ.get('PG_PASSWORD', 'password')

conninfo = f"host={DB_HOST} port={DB_PORT} dbname={DB_NAME} user={DB_USER} password={DB_PASSWORD}"

try:
    with psycopg.connect(conninfo) as conn:
        with conn.cursor() as cur:
            # Create a table
            cur.execute("""
                CREATE TABLE IF NOT EXISTS my_data (
                    id SERIAL PRIMARY KEY,
                    value TEXT
                )
            """)

            # Insert data
            cur.execute("INSERT INTO my_data (value) VALUES (%s)", ("Hello Psycopg C!",))
            conn.commit()

            # Query data
            cur.execute("SELECT id, value FROM my_data ORDER BY id DESC LIMIT 1")
            record = cur.fetchone()
            print(f"Inserted and retrieved: {record}")

except psycopg.Error as e:
    print(f"Database error: {e}")
    # In a real application, you might want to rollback on error
    # if 'conn' is available and not in autocommit mode.
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →