PyGreSQL

6.2.3 · active · verified Thu Apr 16

PyGreSQL is a Python module that provides an interface to PostgreSQL databases, wrapping the lower-level C API library `libpq`. It allows Python applications to leverage powerful PostgreSQL features directly from Python. The current stable version is 6.2.3, released on January 25, 2026, and it primarily supports Python 3.8 to 3.14 and PostgreSQL 12 to 18. The project is actively maintained.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a PostgreSQL database using PyGreSQL's classic interface, create a table (if it doesn't exist), insert data, and fetch results. It uses environment variables for connection parameters for security and flexibility.

import os
from pg import DB

dbname = os.environ.get('PG_DBNAME', 'testdb')
host = os.environ.get('PG_HOST', 'localhost')
port = int(os.environ.get('PG_PORT', 5432))
user = os.environ.get('PG_USER', 'postgres')
passwd = os.environ.get('PG_PASSWORD', 'mysecretpassword')

conn = None
try:
    # Connect using the classic interface
    conn = DB(dbname=dbname, host=host, port=port, user=user, passwd=passwd)
    print(f"Successfully connected to PostgreSQL database '{dbname}'")

    # Execute a simple query
    conn.query("CREATE TABLE IF NOT EXISTS test_table (id SERIAL PRIMARY KEY, name VARCHAR(255))")
    print("Table 'test_table' ensured to exist.")

    # Insert data
    insert_result = conn.insert('test_table', name='PyGreSQL Example')
    print(f"Inserted data: {insert_result}")

    # Fetch data
    results = conn.query("SELECT id, name FROM test_table").getresult()
    print("Fetched data:")
    for row_id, row_name in results:
        print(f"  ID: {row_id}, Name: {row_name}")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    if conn:
        conn.close()
        print("Database connection closed.")

view raw JSON →