实现说明
真正干活的是函数 seed、main,其余都是接线。
closing、Path、TemporaryDirectory 是从 sqlite3 借来的全部符号——耦合显式而窄。
使用要点
- 依赖外部包
sqlite3,运行前需要先安装。 - 演示输出是带标签的(
rows copied:、integrity:、backup size:),每个操作都会留下自己的一行标注。 main的演示流程是seed——跑一遍文件,这条流程从头到尾可见。
常见问题
要先安装哪些包?
需要。导入解析到 sqlite3,由包管理器提供。
入口签名:def seed(path: Path) -> None
核心语句
with closing(sqlite3.connect(backup_path)) as copy:
count = copy.execute('SELECT COUNT(*) FROM events').fetchone()[0]
integrity = copy.execute('PRAGMA integrity_check').fetchone()[0]
print('rows copied:', count)
print('integrity:', integrity)
print('backup size:', backup_path.stat().st_size)
with closing(sqlite3.connect(path)) as connection:
connection.execute('CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT)')
connection.executemany(
'INSERT INTO events (kind) VALUES (?)',
[('click',), ('view',), ('purchase',)],
)
connection.commit()
代码示例
import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory
def seed(path: Path) -> None:
with closing(sqlite3.connect(path)) as connection:
connection.execute('CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT)')
connection.executemany(
'INSERT INTO events (kind) VALUES (?)',
[('click',), ('view',), ('purchase',)],
)
connection.commit()
def main() -> None:
with TemporaryDirectory() as tmp:
source_path = Path(tmp) / 'source.db'
backup_path = Path(tmp) / 'backup.db'
seed(source_path)
source = sqlite3.connect(source_path)
target = sqlite3.connect(backup_path)
source.backup(target, pages=1)
target.close()
source.close()
# closing() closes the connection even if a query raises.
with closing(sqlite3.connect(backup_path)) as copy:
count = copy.execute('SELECT COUNT(*) FROM events').fetchone()[0]
integrity = copy.execute('PRAGMA integrity_check').fetchone()[0]
print('rows copied:', count)
print('integrity:', integrity)
print('backup size:', backup_path.stat().st_size)
if __name__ == '__main__':
main()