Python sqlite3 怎么只备份 ATTACH 挂载的 SQLite 数据库?
用 sqlite3.Connection.backup 的 name 参数把历史库复制到独立文件,再只读打开并核对表和订单。
单个 SQLite 连接能同时操作当前订单主库和通过 ATTACH 挂载的历史库。若月底仅归档已结账订单,直接执行 source.backup(target) 默认复制的是主库。为确保备份文件仅包含历史数据,必须在调用时显式指定附加库的别名。
用 ATTACH 别名指定备份源
执行 ATTACH DATABASE ? AS history 将历史文件接入源连接,其中 history 是该连接内部的逻辑别名,与磁盘物理文件名无关。若省略 backup() 的 name 参数,SQLite 默认备份源连接的 main 库。明确设置 name="history" 后,会将历史库的内容写入目标连接的 main 库中。
事务提交后执行历史库备份
示例代码在临时目录生成三个独立文件。示例在主库创建 active_orders 表,附加库创建 closed_orders 表并插入订单 501。数据提交后,打开一个新的目标文件进行备份。由于备份操作会覆盖目标库原有内容,每次备份应针对单独的目标文件,并通过参数选择特定的源库。
import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
source_path = Path(directory) / "orders.db"
history_path = Path(directory) / "history.db"
archive_path = Path(directory) / "history-backup.db"
with closing(sqlite3.connect(source_path)) as source:
source.execute("CREATE TABLE active_orders (id INTEGER PRIMARY KEY)")
source.execute("ATTACH DATABASE ? AS history", (str(history_path),))
source.execute(
"CREATE TABLE history.closed_orders "
"(id INTEGER PRIMARY KEY, amount_cents INTEGER NOT NULL)"
)
source.execute("INSERT INTO history.closed_orders VALUES (?, ?)", (501, 3590))
source.commit()
with closing(sqlite3.connect(archive_path)) as target:
source.backup(target, name="history")
with closing(sqlite3.connect(archive_path.as_uri() + "?mode=ro", uri=True)) as archive:
tables = archive.execute(
"SELECT name FROM main.sqlite_master WHERE type = 'table' ORDER BY name"
).fetchall()
orders = archive.execute(
"SELECT id, amount_cents FROM main.closed_orders ORDER BY id"
).fetchall()
print("备份文件中的表", tables)
print("归档订单", orders)
预期输出
备份文件中的表 [('closed_orders',)]
归档订单 [(501, 3590)]
以只读模式 mode=ro 重新打开备份文件,检查时不会写入归档。该文件作为新连接的主库直接打开,无需再次使用 history 别名挂载。通过查询 main.sqlite_master 确认归档中仅存在 closed_orders 表,并查询订单 501,核对这条记录的金额。
排查备份中误含主库表的问题
若备份中出现 active_orders 表,需检查执行备份的连接是否已正确执行 ATTACH,以及 name 参数是否被遗漏或错误设置为 main。各连接的附加库别名相互独立,可在执行备份的连接上运行 PRAGMA database_list,核对别名与实际文件的映射关系。
在 PRAGMA database_list 的结果中,第二列代表连接内的数据库名称,第三列为文件路径。定位到第三列匹配历史文件的那一行,提取其第二列的值作为 name 参数传入。若查询结果中未包含历史文件,说明该连接尚未挂载,需先执行附加操作。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













