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

Cursor — execute, fetchone, fetchall

~12 min · python, cursor, fetch

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

실행 단위

모든 SQL statement 가 cursor 통해 실행. conn.execute(sql, params) 가 한 개 반환 (호출마다 fresh cursor). Row 읽기:

  • cursor.fetchone() — 다음 row tuple, 또는 None.
  • cursor.fetchmany(n) — n row 까지 list of tuple.
  • cursor.fetchall() — 남은 row 다 (주의: 거대할 수 있음).
  • Iterationfor row in cursor: 가 lazy stream; 큰 결과 set 의 idiomatic.
Tip: Iteration 기본. 백만 row query 의 fetchall() 이 백만 tuple 메모리 할당; iterator 는 한 번에 하나 stream.

Code

Read 3 가지·python
import sqlite3

conn = sqlite3.connect('demo.db')

# fetchone — 단일 row
row = conn.execute('SELECT * FROM users WHERE id = ?', (1,)).fetchone()
print(row)  # tuple 또는 None

# fetchmany — 제한 batch
batch = conn.execute('SELECT * FROM users LIMIT 100').fetchmany(20)
print(len(batch), 'rows')

# Iterate — streaming, 큰 결과의 idiomatic
for user_id, email in conn.execute('SELECT id, email FROM users'):
    print(user_id, email)
Cursor metadata·python
cur = conn.execute('SELECT id, email, username FROM users LIMIT 1')
print(cur.description)
# (('id', None, ...), ('email', None, ...), ('username', None, ...))

print([d[0] for d in cur.description])
# ['id', 'email', 'username']

# Execute 후 INSERT 면 lastrowid 설정
cur = conn.execute('INSERT INTO users(email) VALUES (?)', ('z@x.com',))
print(cur.lastrowid)
# 42

External links

Exercise

Query 의 row 한 번에 하나씩 yield 하는 generator 함수 — cursor iteration 사용. 100k row 테이블 처리, peak 메모리 낮게 유지 확인 (tracemalloc 또는 OS process monitor). 그 다음 fetchall() 로 다시 — 차이 관찰.

Progress

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

댓글 0

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

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