Python

Bulk Insert with executemany

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Insert many rows in one round-trip using executemany. Orders-of-magnitude faster than a loop of single inserts — and the driver handles batching/parametrization for you.
Python
Raw
import sqlite3

def bulk_insert(db: sqlite3.Connection, table: str, rows: list[dict]) -> int:
    if not rows:
        return 0
    cols = list(rows[0].keys())
    placeholders = ", ".join(f":{c}" for c in cols)
    col_list     = ", ".join(cols)
    db.executemany(f"INSERT INTO {table} ({col_list}) VALUES ({placeholders})", rows)
    return len(rows)

with sqlite3.connect("app.db") as db:
    db.execute("CREATE TABLE IF NOT EXISTS events (id INTEGER PRIMARY KEY, user_id INTEGER, name TEXT)")
    bulk_insert(db, "events", [
        {"user_id": 1, "name": "login"},
        {"user_id": 1, "name": "view_page"},
        {"user_id": 2, "name": "signup"},
    ])
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.