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

executemany — 빠른 bulk 연산

~10 min · python, bulk, executemany, performance

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

Python 이 아니라 C 에서 루프

executemany 가 SQL statement + parameter tuple iterable 받음. 드라이버가 C 에서 루프, prepared statement 재사용. Bulk insert 면 Python for 루프의 row 마다 execute 보다 극적으로 빠름 — single transaction 과 자연스럽게 짝.

3 가지 룰:

  • >= 100 row write 면 항상.
  • Transaction (with conn:) 으로 감싸.
  • 매우 큰 batch 는 1k–10k row 로 chunk — 메모리/락 시간 sane 유지.
Tip: executemany + transaction 이 보통 'insert 느낌 느림' 과 'insert 느낌 공짜' 의 차이. SQLite 느리다 보고의 가장 흔한 원인 = transaction 빠짐.

Code

Chunking 있는 executemany·python
import sqlite3, itertools

def chunks(iterable, n):
    it = iter(iterable)
    while True:
        batch = list(itertools.islice(it, n))
        if not batch:
            return
        yield batch

conn = sqlite3.connect('demo.db')
conn.execute('PRAGMA journal_mode = WAL')

rows = ((f'u{i}@x.com', f'user{i}') for i in range(100_000))

for batch in chunks(rows, 5_000):
    with conn:
        conn.executemany('INSERT INTO users(email, username) VALUES (?, ?)', batch)

External links

Exercise

50,000 row insert 4 방식 벤치마크: (a) execute + autocommit 루프, (b) execute + 한 transaction 루프, (c) 한 큰 호출 executemany, (d) 5,000 chunk + chunk 마다 transaction 의 executemany. 시간 print/plot. Gap 설명.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.