在Python中,可以使用sqlite3
库来操作SQLite数据库,因为这个库是Python标准库的一部分,所以不需要额外安装。以下是使用sqlite3
库进行数据库备份和恢复的步骤:
import sqlite3
import shutil
import os
def backup_database(source_db, target_db):
# 连接到源数据库
conn = sqlite3.connect(source_db)
cursor = conn.cursor()
# 获取源数据库的名称
source_name = os.path.basename(source_db)
# 创建目标数据库文件
if not os.path.exists(target_db):
with sqlite3.connect(target_db) as target_conn:
target_conn.execute(f"CREATE TABLE {source_name} (id INTEGER PRIMARY KEY, data TEXT);")
# 复制表结构和数据
for table_name in cursor.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
cursor.execute(f"SELECT * FROM {table_name[0]};")
rows = cursor.fetchall()
column_names = [description[0] for description in cursor.description]
with sqlite3.connect(target_db) as target_conn:
target_conn.executemany(f"INSERT INTO {table_name[0]} VALUES ({','.join(['?']*len(column_names))});", rows)
# 关闭源数据库连接
cursor.close()
conn.close()
print(f"Backup of {source_db} completed and saved to {target_db}")
def restore_database(source_db, target_db):
# 连接到源数据库
conn = sqlite3.connect(source_db)
cursor = conn.cursor()
# 获取源数据库的名称
source_name = os.path.basename(source_db)
# 检查目标数据库是否存在,如果存在则删除
if os.path.exists(target_db):
os.remove(target_db)
# 创建目标数据库文件
with sqlite3.connect(target_db) as target_conn:
target_conn.execute(f"CREATE TABLE {source_name} (id INTEGER PRIMARY KEY, data TEXT);")
# 复制表结构和数据
for table_name in cursor.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
cursor.execute(f"SELECT * FROM {table_name[0]};")
rows = cursor.fetchall()
column_names = [description[0] for description in cursor.description]
with sqlite3.connect(target_db) as target_conn:
target_conn.executemany(f"INSERT INTO {table_name[0]} VALUES ({','.join(['?']*len(column_names))});", rows)
# 关闭源数据库连接
cursor.close()
conn.close()
print(f"Restore of {source_db} completed and saved to {target_db}")
# 备份数据库
backup_database('source.db', 'backup.db')
# 恢复数据库
restore_database('backup.db', 'restored_source.db')
请注意,这些示例适用于SQLite数据库。对于其他数据库系统(如MySQL、PostgreSQL等),你需要使用相应的Python库(如mysql-connector-python
、psycopg2
等)并遵循相应的备份和恢复过程。