records

repository·master·Indexed 27 days ago

https://github.com/kennethreitz/records

A lightweight Python library for executing raw SQL queries against relational databases. It supports RedShift, Postgres, MySQL, SQLite, Oracle, and MS-SQL, providing an interface for handling results, safe parameterization, transaction management, and exporting data to formats such as CSV, JSON, YAML, HTML, and Pandas DataFrames via Tablib.

Tokens
482
Snippets
2
Records
6
Agent score
43%

What's inside records

  1. Connect to a database and execute queries

    master

    Use records.Database to establish a connection via a connection string. You can execute raw SQL strings using .query() or load SQL from a file using .query_file(). Supported databases include RedShift, Postgres, MySQL, SQLite, Oracle, and MS-SQL (drivers not included).

    import records
    
    db = records.Database('postgres://...')
    rows = db.query('select * from active_users')    # or db.query_file('sqls/active-users.sql')
  2. Export query results to various formats

    master

    Records integrates with Tablib to allow exporting query results to multiple formats using the .export(format) method. Supported formats include:

    • csv (Comma Separated Values)
    • yaml (YAML)
    • json (JSON)
    • xls or xlsx (Microsoft Excel)
    • df (Pandas DataFrame)
    • html (HTML Tables)

    Note: For Excel exports, you must write the returned bytes to a file.

  3. Access and iterate over query results

    master

    Query results can be iterated over directly or accessed by index. Individual records allow field access via attribute name (row.field), dictionary key (row['field']), or integer index (row[index]). Fields with non-alphanumeric characters are supported.

    Key methods for result sets:

    • rows.all(): Returns a list of all records.
    • rows.first(): Returns only the first record.
    • rows.as_dict(): Returns results as a dictionary.
    • rows.as_dict(ordered=True): Returns results as an ordered dictionary.