溫馨提示×

Python數據庫連接怎樣進行數據庫的備份與恢復

小樊
122
2024-11-09 14:21:52
欄目: 編程語言

在Python中,可以使用sqlite3庫來操作SQLite數據庫,因為這個庫是Python標準庫的一部分,所以不需要額外安裝。以下是使用sqlite3庫進行數據庫備份和恢復的步驟:

  1. 導入必要的模塊:
import sqlite3
import shutil
import os
  1. 創建一個函數來執行數據庫備份:
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}")
  1. 創建一個函數來執行數據庫恢復:
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}")
  1. 使用這些函數來備份和恢復數據庫:
# 備份數據庫
backup_database('source.db', 'backup.db')

# 恢復數據庫
restore_database('backup.db', 'restored_source.db')

請注意,這些示例適用于SQLite數據庫。對于其他數據庫系統(如MySQL、PostgreSQL等),你需要使用相應的Python庫(如mysql-connector-python、psycopg2等)并遵循相應的備份和恢復過程。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女