PostgreSQL Database Wrapper

0.0.11 · maintenance · verified Fri Apr 17

pgdb is a lightweight Python wrapper around `psycopg2-binary` designed to simplify basic interactions with PostgreSQL databases. It provides a simple API for connecting, executing queries, and fetching results. The library, currently at version 0.0.11, appears to be in maintenance mode with its last update over two years ago.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection, create a table, insert data, and fetch results using `pgdb`. It utilizes environment variables for database credentials, falling back to common defaults for local testing. It also includes basic error handling and resource cleanup.

import pgdb
import os

DB_HOST = os.environ.get('PGDB_HOST', 'localhost')
DB_NAME = os.environ.get('PGDB_DATABASE', 'test_db')
DB_USER = os.environ.get('PGDB_USER', 'postgres')
DB_PASS = os.environ.get('PGDB_PASSWORD', 'mysecretpassword') # REMEMBER to change in prod

conn = None
try:
    conn = pgdb.connect(host=DB_HOST, database=DB_NAME, user=DB_USER, password=DB_PASS)
    cursor = conn.cursor()

    # Cleanup for re-runs and create table
    cursor.execute("DROP TABLE IF EXISTS example_data;")
    cursor.execute("CREATE TABLE example_data (id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL);")
    conn.commit()

    # Insert data
    cursor.execute("INSERT INTO example_data (name) VALUES ('Alice'), ('Bob'), ('Charlie');")
    conn.commit()

    # Fetch and print data
    cursor.execute("SELECT id, name FROM example_data;")
    print("Fetched data:")
    for row in cursor.fetchall():
        print(row)

except pgdb.Error as e:
    print(f"Database error: {e}")
    if conn:
        conn.rollback() # Rollback on error
finally:
    if conn:
        conn.close()

view raw JSON →