Queries

2.1.1 · active · verified Thu Apr 16

Queries is a BSD licensed opinionated wrapper of the `psycopg2` library for interacting with PostgreSQL. It aims to reduce the complexity of `psycopg2` while adding features like a simplified API, connection pooling, and asynchronous support for Tornado. The library supports Python 2.7+ and 3.4+ and is currently at version 2.1.1.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a PostgreSQL database using `queries.Session`, create a table, insert data, and retrieve results. It utilizes environment variables for the database URI for flexible configuration.

import os
from queries import Session

# Configure your PostgreSQL connection URI
# Example: "postgresql://user:password@host:port/database_name"
# If omitted, defaults to "postgresql://<current_os_user>@localhost:5432/<current_os_user>"
DB_URI = os.environ.get('POSTGRES_URI', 'postgresql://postgres@localhost:5432/postgres')

def main():
    try:
        with Session(DB_URI) as session:
            # Create a table
            session.query("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(255))")
            print("Table 'users' ensured.")

            # Insert data
            result = session.query("INSERT INTO users (name) VALUES (%s) RETURNING id", ('Alice',))
            new_id = result.scalar()
            print(f"Inserted user Alice with ID: {new_id}")

            # Query data
            results = session.query("SELECT id, name FROM users")
            print("Current users:")
            for row in results:
                print(f"  ID: {row.id}, Name: {row.name}")

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == '__main__':
    main()

view raw JSON →