实现说明
使用上下文管理器的 SQLite 连接以函数 fetch_users、create_schema为骨架。
从 sqlite3 借的东西一行可见:closing、List、Tuple。
结果是全新构造,调用方可以放心保留自己的原件。
使用要点
sqlite3必须先装好——示例直接导入它们。- 把
fetch_users当作 API:导入它,其余代码可以忽略。
常见问题
fetch_users 会修改传入的参数吗?
不会——返回值是新建的,入参从不被写入。
有第三方依赖吗?
sqlite3——运行前用包管理器装上。
主要签名是 def fetch_users(db_path: str) -> List[Tuple[int, str]]
核心语句
def create_schema(connection: sqlite3.Connection) -> None:
connection.execute(
"CREATE TABLE IF NOT EXISTS users ("
"id INTEGER PRIMARY KEY, email TEXT NOT NULL, active INTEGER DEFAULT 0)"
)
with closing(sqlite3.connect(db_path)) as connection:
connection.row_factory = sqlite3.Row
with connection:
cursor = connection.execute(
"SELECT id, email FROM users WHERE active = ?", (1,)
)
rows = cursor.fetchall()
代码示例
import sqlite3
from contextlib import closing
from typing import List, Tuple
def fetch_users(db_path: str) -> List[Tuple[int, str]]:
with closing(sqlite3.connect(db_path)) as connection:
connection.row_factory = sqlite3.Row
with connection:
cursor = connection.execute(
"SELECT id, email FROM users WHERE active = ?", (1,)
)
rows = cursor.fetchall()
return [(row["id"], row["email"]) for row in rows]
def create_schema(connection: sqlite3.Connection) -> None:
connection.execute(
"CREATE TABLE IF NOT EXISTS users ("
"id INTEGER PRIMARY KEY, email TEXT NOT NULL, active INTEGER DEFAULT 0)"
)