C.W.K.
Stream
Lesson 02 of 10 · published

aiosqlite — The Async Wrapper

~12 min · aiosqlite, async, wrapper

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Same API, with await sprinkled on top

aiosqlite wraps the standard sqlite3 module so you can await every operation. Internally it pushes each call onto a single background thread per connection — the event loop is never blocked.

pip install aiosqlite

The shapes that matter:

  • aiosqlite.connect(path) — async context manager that yields a connection.
  • conn.execute(sql, params) — returns an async cursor.
  • await cursor.fetchone(), await cursor.fetchall().
  • async for row in conn.execute(...) — streaming iteration.
  • conn.row_factory = aiosqlite.Row — same dict-like rows as sync sqlite3.
Tip: Set the same PRAGMAs you set in sync sqlite3 — WAL, foreign_keys, busy_timeout. aiosqlite forwards them to the underlying connection unchanged.

Code

Hello, aiosqlite·python
import asyncio, aiosqlite

async def main():
    async with aiosqlite.connect('demo.db') as conn:
        conn.row_factory = aiosqlite.Row
        await conn.execute('PRAGMA journal_mode = WAL')
        await conn.execute('PRAGMA foreign_keys = ON')
        await conn.execute(
            'CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, body TEXT)'
        )
        await conn.execute('INSERT INTO notes(body) VALUES (?)', ('hello',))
        await conn.commit()

        async with conn.execute('SELECT * FROM notes') as cur:
            async for row in cur:
                print(dict(row))

asyncio.run(main())

External links

Exercise

Take any synchronous sqlite3 script you have and port it to aiosqlite. Confirm the API translation is mostly mechanical (add async/await, switch to context managers, swap row factory). Then run a small concurrency test: 100 async tasks each doing a short query against the same database. Compare to the same code with sync sqlite3 + threads.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.