我的数据库格式不正确。当我尝试从两个表中的任何一个获取记录时,它会抛出异常:
DatabaseError: database disk image is malformed
我知道通过命令行我可以做到这一点:
sqlite3 ".dump" base.db | sqlite3 new.db
我可以在 Python 中做这样的事情吗?
最佳答案
据我所知你不能那样做(唉,我可能弄错了),因为 python 的 sqlite3 模块非常有限。
我能想到的唯一解决方法是调用 os 命令 shell(例如终端、cmd 等)(more info)通过 pythons call-command:
将其与来自 here 的信息结合起来做这样的事情:
这是在 windows xp 机器上完成的: 不幸的是我现在不能在 unix 机器上测试它 - 希望它能帮助你:
from subprocess import check_call
def sqliterepair():
check_call(["sqlite3", "C:/sqlite-tools/base.db", ".mode insert", ".output C:/sqlite-tools/dump_all.sql", ".dump", ".exit"])
check_call(["sqlite3", "C:/sqlite-tools/new.db", ".read C:/sqlite-tools/dump_all.sql", ".exit"])
return
第一个参数是调用 sqlite3.exe。因为它在我的系统路径变量中,所以我不需要指定路径或后缀“.exe”。 其他参数链接到 sqlite3-shell。
请注意,参数“.exit”是必需的,因此 sqlite-shell 将退出。否则 check_call() 将永远不会完成,因为外部 cmd-shell 或终端将处于暂停状态。
当然之后应该删除转储文件...
编辑: 更短的解决方案(归功于 OP(见评论))
os.system("sqlite3 C:/sqlite-tools/base.db .dump | sqlite3 C:/sqlite-tools/target.db")
刚刚测试过这个:它有效。显然我在评论中错了。
关于python - 在 Python 中从格式错误的 SQLite 中转储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34882164/