Asynchronous Database Toolkit

0.9.0 · active · verified Sat Apr 11

The `databases` library provides asynchronous database support for Python, designed to work with `asyncio` and `await`. It supports PostgreSQL, MySQL, and SQLite, and integrates well with SQLAlchemy Core expression language. The current version is 0.9.0, and it has an active development cadence with regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates connecting to a database, executing a DDL statement to create a table, inserting a record, and fetching all records. It uses an in-memory SQLite database by default but can be configured with an environment variable for other databases. Remember to install the appropriate database driver (e.g., `pip install databases[sqlite]`).

import asyncio
import os
from databases import Database

async def main():
    # Use an in-memory SQLite database for a simple example.
    # For a real application, use a proper URL like DATABASE_URL = 'postgresql://user:pass@host/db'
    database = Database(os.environ.get('DATABASE_URL', 'sqlite:///./test.db'))

    try:
        await database.connect()
        print("Database connected.")

        # Create a table
        query = """
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY,
                name VARCHAR(100)
            );
        """
        await database.execute(query=query)
        print("Table 'users' created or already exists.")

        # Insert data
        query = "INSERT INTO users(name) VALUES (:name)"
        await database.execute(query=query, values={"name": "Alice"})
        print("Inserted 'Alice'.")

        # Select data
        query = "SELECT id, name FROM users"
        rows = await database.fetch_all(query=query)
        for row in rows:
            print(f"User: {row['id']}, {row['name']}")

    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        await database.disconnect()
        print("Database disconnected.")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →