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

Async Cursors, Iteration, and Transactions

~12 min · aiosqlite, transactions, iteration

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

Same patterns, async-flavored

Cursors in aiosqlite are async context managers. Iteration uses async for. Transactions use async with on the connection or explicit BEGIN/COMMIT — same semantics as sync, with awaits.

Tip: async with conn: behaves like with conn: in sync sqlite3 — implicit BEGIN on entry, COMMIT on success, ROLLBACK on exception. It's the everyday transaction pattern in async code.

Code

Cursor + iteration + transaction·python
import aiosqlite

async def write_chunk(conn, rows):
    async with conn:                        # BEGIN/COMMIT/ROLLBACK context
        await conn.executemany(
            'INSERT INTO notes(body) VALUES (?)',
            rows,
        )

async def stream_all(conn):
    async with conn.execute('SELECT id, body FROM notes ORDER BY id') as cur:
        async for row in cur:
            yield row

async def main():
    async with aiosqlite.connect('demo.db') as conn:
        conn.row_factory = aiosqlite.Row
        await write_chunk(conn, [(f'note{i}',) for i in range(1000)])
        async for row in stream_all(conn):
            print(dict(row))

External links

Exercise

Write an async function that bulk-imports 100k rows into SQLite using aiosqlite + executemany inside a transaction. Time it. Then add a deliberate exception halfway through and confirm the transaction rolled back (no rows visible after).

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.