在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
等)并遵循相應的備份和恢復過程。