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

시작하기 — import sqlite3

~12 min · python, sqlite3, stdlib

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

이미 깔려 있고, 이미 쓸만함

Python 이 stdlib 에 sqlite3 ship. pip install X, 추가 의존성 X. CPython 과 같이 오는 C SQLite 라이브러리 wrap.

최소 사용:

import sqlite3
conn = sqlite3.connect('myapp.db')
conn.execute('CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, body TEXT)')
conn.execute('INSERT INTO notes(body) VALUES (?)', ('hello',))
conn.commit()
for row in conn.execute('SELECT * FROM notes'):
    print(row)
conn.close()

되긴 해, 근데 알아야 할 거 대부분 skip. 다음 9 lesson 이 그거 채움. 첫 체크:

  • sqlite3.sqlite_version — 번들 libsqlite 버전 (시스템 CLI 보다 옛날일 때 많음).
  • sqlite3.version — Python 모듈 버전 (덜 흥미).
  • dict-like access 위해 conn.row_factory = sqlite3.Row — py05.
Tip: CLI sqlite3 가 Python 번들 libsqlite 보다 훨씬 새로우면 pysqlite3-binary 깔고 그거 import — 같은 API, 새 엔진, STRICT/JSONB/etc 지원.

Code

Hello, sqlite3·python
import sqlite3
print('libsqlite:', sqlite3.sqlite_version)
print('module:   ', sqlite3.version)

conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE t(id INTEGER PRIMARY KEY, v TEXT)')
conn.execute('INSERT INTO t(v) VALUES (?)', ('hello',))
conn.commit()
print(conn.execute('SELECT * FROM t').fetchall())
conn.close()

External links

Exercise

번들 libsqlite 가 이 quest 사용 기능 지원하는지 확인: STRICT (3.37+), RETURNING (3.35+), JSONB (3.45+). 안 하면 pysqlite3-binary 깔고 버전 재확인. 그 다음 10 줄 스크립트: DB 생성, STRICT 테이블 만들기, row insert, select.

Progress

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

댓글 0

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

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