Records: SQL for Humans

0.6.0 · active · verified Wed Apr 15

Records is a simple yet powerful Python library designed for making raw SQL queries to various relational databases with an elegant interface. It aims to reduce boilerplate code associated with common database tasks. The current version, 0.6.0, includes support for SQLAlchemy v2, making it compatible with modern database backends. Releases are infrequent but tend to include significant updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a database (using an in-memory SQLite by default or a URL from an environment variable), execute a parameterized query, iterate through results, and access data from a `Record` object. It highlights basic CRUD operations and the importance of parameterized queries for security.

import records
import os

# Example using SQLite in-memory or a database URL from an environment variable
# For other databases, change the connection string, e.g., 
# "postgres://user:pass@host:port/dbname"
database_url = os.environ.get('DATABASE_URL', 'sqlite:///:memory:')
db = records.Database(database_url)

# Create a table and insert data (example for SQLite)
if 'sqlite' in database_url:
    db.query('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
    db.query('INSERT INTO users (name, age) VALUES (:name, :age)', name='Alice', age=30)
    db.query('INSERT INTO users (name, age) VALUES (:name, :age)', name='Bob', age=24)

# Run a query
rows = db.query('SELECT * FROM users WHERE age > :min_age', min_age=25)

# Iterate over results
print('Users over 25:')
for row in rows:
    print(f"  Name: {row.name}, Age: {row.age}")

# Access columns by name or index
first_row = rows.first()
if first_row:
    print(f"First user found: {first_row.name}")

# Export to CSV (requires tablib)
# print(rows.export('csv'))

# Export to Pandas DataFrame (requires pandas)
# df = rows.export('df')
# print(df.head())

# Close the connection (important for some databases)
db.close()

view raw JSON →