AsyncIO SQLite

raw JSON →
0.22.1 verified Tue May 12 auth: no python install: verified quickstart: verified

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.

pip install aiosqlite
error ModuleNotFoundError: No module named 'aiosqlite'
cause The 'aiosqlite' module is not installed in the Python environment.
fix
Install the module using 'pip install aiosqlite'.
error AttributeError: 'Connection' object has no attribute 'execute'
cause Attempting to call 'execute' directly on a 'Connection' object instead of using a cursor.
fix
Use a cursor to execute queries: 'cursor = await conn.cursor(); await cursor.execute(query)'.
error AttributeError: 'str' object has no attribute 'execute'
cause A string variable is being used as a cursor object, likely due to variable name shadowing.
fix
Ensure variable names do not conflict and that the cursor object is correctly referenced.
error AttributeError: 'Connection' object has no attribute '_execute'
cause Using an outdated or incompatible version of the database driver or library.
fix
Update the database driver or library to a compatible version.
error AttributeError: 'Engine' object has no attribute 'execute'
cause Directly calling 'execute' on an 'Engine' object instead of obtaining a connection first.
fix
Obtain a connection from the engine and then execute: 'with engine.connect() as conn: conn.execute(query)'.
gotcha Encountering 'Database is Locked' errors, especially in concurrent scenarios, is a common SQLite issue. While `aiosqlite` provides an async interface, SQLite itself is a single-file database and can face contention.
fix Increase the `timeout` parameter when calling `aiosqlite.connect()` to allow SQLite more time to acquire locks (e.g., `aiosqlite.connect('db.db', timeout=10)`). Consider optimizing database schemas, queries, or using a connection pool (`aiosqlitepool`) for high-concurrency applications.
breaking Older Python versions are no longer supported. Python 3.7 and 3.8 support was dropped in versions 0.20.0 and 0.21.0 respectively.
fix Ensure your project runs on Python 3.9 or newer. Upgrade your Python environment if using an older version.
breaking When used with SQLAlchemy, `aiosqlite` versions 0.22.0 and above changed the internal connection class, which is no longer a daemon thread. This can cause applications to hang on exit if SQLAlchemy's `aiosqlite` dialect doesn't explicitly call `await engine.dispose()` to close connections.
fix If using SQLAlchemy with `aiosqlite >= 0.22.0`, ensure you explicitly call `await engine.dispose()` at the end of your application's main function to properly close all connections and avoid hanging processes. Alternatively, disable connection pooling by using `NullPool`.
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.11s 17.9M
3.10 alpine (musl) - - 0.11s 17.9M
3.10 slim (glibc) wheel 1.5s 0.08s 18M
3.10 slim (glibc) - - 0.07s 18M
3.11 alpine (musl) wheel - 0.19s 19.8M
3.11 alpine (musl) - - 0.21s 19.8M
3.11 slim (glibc) wheel 1.6s 0.18s 20M
3.11 slim (glibc) - - 0.15s 20M
3.12 alpine (musl) wheel - 0.42s 11.7M
3.12 alpine (musl) - - 0.41s 11.7M
3.12 slim (glibc) wheel 1.4s 0.37s 12M
3.12 slim (glibc) - - 0.38s 12M
3.13 alpine (musl) wheel - 0.42s 11.4M
3.13 alpine (musl) - - 0.41s 11.3M
3.13 slim (glibc) wheel 1.5s 0.35s 12M
3.13 slim (glibc) - - 0.37s 12M
3.9 alpine (musl) wheel - 0.10s 17.4M
3.9 alpine (musl) - - 0.11s 17.4M
3.9 slim (glibc) wheel 1.7s 0.09s 18M
3.9 slim (glibc) - - 0.09s 18M

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())