AsyncIO SQLite

0.22.1 · active · verified Sat Mar 28

aiosqlite provides a friendly, async interface to SQLite databases, replicating the standard `sqlite3` module but with asynchronous versions of all connection and cursor methods. It enables interaction with SQLite databases on the main AsyncIO event loop without blocking, utilizing a single, shared thread per connection for query execution. The current version is 0.22.1, and it maintains an active release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a database, defining a table, inserting, querying, updating, and deleting data using `aiosqlite`'s async context managers for connections and cursors. It ensures proper resource management by automatically committing transactions and closing connections.

import asyncio
import aiosqlite
import os

async def main():
    db_path = os.environ.get('AIOSQLITE_DB_PATH', 'my_database.db')
    async with aiosqlite.connect(db_path) as db:
        # Create a table
        await db.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                age INTEGER
            )
        ''')
        await db.commit()

        # Insert data
        await db.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 30))
        await db.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Bob", 24))
        await db.commit()

        # Query data
        async with db.execute("SELECT id, name, age FROM users WHERE age > ?", (25,)) as cursor:
            print("Users older than 25:")
            async for row in cursor:
                print(f"  ID: {row[0]}, Name: {row[1]}, Age: {row[2]}")

        # Update data
        await db.execute("UPDATE users SET age = ? WHERE name = ?", (31, "Alice"))
        await db.commit()

        # Delete data
        await db.execute("DELETE FROM users WHERE name = ?", ("Bob",))
        await db.commit()

        async with db.execute("SELECT COUNT(*) FROM users") as cursor:
            (count,) = await cursor.fetchone()
            print(f"Total users remaining: {count}")

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

view raw JSON →