WeChatMsg/app/DataBase/merge.py

57 lines
1.7 KiB
Python
Raw Normal View History

2023-11-29 21:23:44 +08:00
import os
import sqlite3
def merge_databases(source_paths, target_path):
# 创建目标数据库连接
target_conn = sqlite3.connect(target_path)
target_cursor = target_conn.cursor()
try:
# 开始事务
target_conn.execute("BEGIN;")
for i, source_path in enumerate(source_paths):
if not os.path.exists(source_path):
break
db = sqlite3.connect(source_path)
db.text_factory = str
2023-11-29 21:23:44 +08:00
cursor = db.cursor()
sql = '''
2023-11-29 21:39:38 +08:00
SELECT TalkerId,MsgsvrID,Type,SubType,IsSender,CreateTime,Sequence,StrTalker,StrContent,DisplayContent,BytesExtra
2023-11-29 21:23:44 +08:00
FROM MSG;
'''
cursor.execute(sql)
result = cursor.fetchall()
# 附加源数据库
target_cursor.executemany(
2023-11-29 21:39:38 +08:00
"INSERT INTO MSG "
"(TalkerId,MsgsvrID,Type,SubType,IsSender,CreateTime,Sequence,StrTalker,StrContent,DisplayContent,"
"BytesExtra)"
"VALUES(?,?,?,?,?,?,?,?,?,?,?)",
2023-11-29 21:23:44 +08:00
result)
cursor.close()
db.close()
# 提交事务
target_conn.execute("COMMIT;")
except Exception as e:
# 发生异常时回滚事务
target_conn.execute("ROLLBACK;")
raise e
finally:
# 关闭目标数据库连接
target_conn.close()
if __name__ == "__main__":
# 源数据库文件列表
source_databases = ["Msg/MSG1.db", "Msg/MSG2.db", "Msg/MSG3.db"]
# 目标数据库文件
target_database = "Msg/MSG.db"
import shutil
shutil.copy('Msg/MSG0.db', target_database) # 使用一个数据库文件作为模板
# 合并数据库
merge_databases(source_databases, target_database)