」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Python。自動建立 MySQL 資料庫的備份。

Python。自動建立 MySQL 資料庫的備份。

發佈於2024-07-31
瀏覽:816

Python. Automating creation backups of MySQL database.

此脚本自动创建 MySQL 数据库的备份、恢复它们以及管理目标 MySQL 服务器上的数据库和用户创建。

import subprocess
import datetime
import sys
import os

def check_and_create_database(host, port, username, password, database):
    # Command to check if the database exists
    check_database_command = f"mysql -sN --host={host} --port={port} --user={username} --password={password} -e \"SELECT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{database}')\" 2>/dev/null"

    # Execute the command
    output = subprocess.check_output(check_database_command, shell=True)

    # If the output contains b'1', the database exists
    if b'1' in output:
        subprocess.run(check_database_command, shell=True, check=True)
        print(f"Database '{database}' already exists.")
        sys.exit(1)
    else:
        # If the command fails, the database does not exist
        print(f"Database '{database}' does not exist. Creating...")

        # Command to create the database
        create_database_command = f"mysql --host={host} --port={port} --user={username} --password={password} -e 'CREATE DATABASE {database}' 2>/dev/null"
        subprocess.run(create_database_command, shell=True)

def check_and_create_user(host, port, username, password, database, new_username, new_password):
    # Command to check if the user exists
    check_user_command = f"mysql -sN --host={host} --port={port} --user={username} --password={password} -e \"SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '{new_username}')\" 2>/dev/null"

    # Execute the command
    output = subprocess.check_output(check_user_command, shell=True)

    # If the output contains b'1', the user exists
    if b'1' in output:
        print(f"User '{new_username}' already exists.")
        sys.exit(1)
    else:
        # The user does not exist, create it
        print(f"User '{new_username}' does not exist. Creating...")

        # Command to create the user and grant privileges
        create_user_command = f"mysql --host={host} --port={port} --user={username} --password={password} -e \"CREATE USER '{new_username}'@'%' IDENTIFIED BY '{new_password}'; GRANT ALL PRIVILEGES ON {database}.* TO '{new_username}'@'%'; FLUSH PRIVILEGES;\" 2>/dev/null"
        subprocess.run(create_user_command, shell=True)

def backup_mysql_database(host, port, username, password, database, backup_path):

    # Check if the backup directory exists
    if not os.path.exists(backup_path):
        print(f"Error: Backup directory '{backup_path}' does not exist.")
        sys.exit(1)

    # Create a filename for the backup with the current date and time
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    backup_file = f"{backup_path}/{database}_{timestamp}.sql"

    # Command to create a database backup using mysqldump
    dump_command = f"mysqldump --no-tablespaces --host={host} --port={port} --user={username} --password={password} {database} > {backup_file} 2>/dev/null"

    # Execute the mysqldump command
    subprocess.run(dump_command, shell=True)

    return backup_file

def restore_mysql_database(host, port, username, password, database, backup_file):
    # Command to restore a database from a backup using mysql
    restore_command = f"mysql --host={host} --port={port} --user={username} --password={password} {database} /dev/null"

    # Execute the mysql command
    subprocess.run(restore_command, shell=True)

def main():
    # Connection parameters to the source MySQL database
    source_host = "127.0.0.1"
    source_port = "3309"
    source_username = "my_user"
    source_password = "my_password"
    source_database = "my_database"

    # Connection parameters to the target MySQL database
    target_host = "127.0.0.1"
    target_port = "3309"
    new_username = "new_username"
    new_password = "new_password"
    target_database = "my_database_two"

    target_username = "root"
    target_password = "root_password"

    # Path to save the backup locally
    backup_path = "my_dbs_dumps"

    # Check if source_database is different from target_database
    if source_database == target_database:
        print("Error: Source database should be different from target database.")
        sys.exit(1)

    # Check and create the target database if it does not exist
    check_and_create_database(target_host, target_port, target_username, target_password, target_database)

    # Check and create the target user if it does not exist
    check_and_create_user(target_host, target_port, target_username, target_password, target_database, new_username, new_password)

    # Create a backup of the MySQL database
    backup_file = backup_mysql_database(source_host, source_port, source_username, source_password, source_database, backup_path)
    print(f"Database backup created: {backup_file}")

    # Restore the database on the target server from the backup
    restore_mysql_database(target_host, target_port, target_username, target_password, target_database, backup_file)
    print("Database backup restored on the target server.")

if __name__ == "__main__":
    main()

check_and_create_database:
此函数检查 MySQL 服务器上是否存在数据库。如果数据库不存在,则会创建它。它需要主机、端口、用户名、密码和数据库名称等参数来检查或创建。

check_and_create_user:
与数据库函数一样,该函数检查 MySQL 服务器上是否存在用户。如果用户不存在,它将创建用户并授予特定数据库的权限。它还接受主机、端口、用户名、密码、数据库名称、新用户名和新密码等参数。

backup_mysql_database:
此函数使用 mysqldump 执行 MySQL 数据库的备份。它接受主机、端口、用户名、密码、数据库名称和保存备份文件的路径等参数。

restore_mysql_database:
此函数从备份文件恢复 MySQL 数据库。它接受主机、端口、用户名、密码、数据库名称和备份文件路径等参数。

主要的:
这是脚本的主要功能。它为源和目标 MySQL 数据库设置参数,包括连接详细信息、数据库名称和备份路径。然后,它执行检查以确保源数据库和目标数据库不同,如果目标数据库和用户不存在,则创建目标数据库和用户,创建源数据库的备份,最后将备份恢复到目标数据库。

此外,该脚本使用 subprocess 模块执行 MySQL 操作(mysql、mysqldump)的 shell 命令,并执行错误处理和输出重定向(2>/dev/null)以抑制不必要的输出。

如果您正在使用 MySQL 数据库并想要创建自动化,此代码将为您提供帮助。

此代码代表了一个很好的起始模板,用于创建管理 MySQL 数据库的自动化脚本。

dmi@dmi-laptop:~/my_python$ python3 mysql_backup_restore.py 
Database 'my_database_two' does not exist. Creating...
User 'new_username' does not exist. Creating...
Database backup created: my_dbs_dumps/my_database_2024-05-13_20-05-24.sql
Database backup restored on the target server.
dmi@dmi-laptop:~/my_python$ 

[email protected]

版本聲明 本文轉載於:https://dev.to/dm8ry/python-automating-creation-backups-of-mysql-database-2goa?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何使用FormData()處理多個文件上傳?
    如何使用FormData()處理多個文件上傳?
    )處理多個文件輸入時,通常需要處理多個文件上傳時,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    程式設計 發佈於2025-04-20
  • 如何使用不同數量列的聯合數據庫表?
    如何使用不同數量列的聯合數據庫表?
    合併列數不同的表 當嘗試合併列數不同的數據庫表時,可能會遇到挑戰。一種直接的方法是在列數較少的表中,為缺失的列追加空值。 例如,考慮兩個表,表 A 和表 B,其中表 A 的列數多於表 B。為了合併這些表,同時處理表 B 中缺失的列,請按照以下步驟操作: 確定表 B 中缺失的列,並將它們添加到表的...
    程式設計 發佈於2025-04-20
  • Go語言垃圾回收如何處理切片內存?
    Go語言垃圾回收如何處理切片內存?
    在Go Slices中的垃圾收集:詳細的分析在GO中,Slice是一個動態數組,引用了基礎陣列。使用切片時,了解垃圾收集行為至關重要,以避免潛在的內存洩漏。 考慮使用slice使用slice的以下實現:字符串{ R:=(*Q)[0] *q =(*q)[1:len(*q)] 返...
    程式設計 發佈於2025-04-20
  • 如何干淨地刪除匿名JavaScript事件處理程序?
    如何干淨地刪除匿名JavaScript事件處理程序?
    刪除匿名事件偵聽器將匿名事件偵聽器添加到元素中會提供靈活性和簡單性,但是當要刪除它們時,可以構成挑戰,而無需替換元素本身就可以替換一個問題。 element? element.addeventlistener(event,function(){/在這里工作/},false); 要解決此問題,請考...
    程式設計 發佈於2025-04-20
  • 如何從PHP中的數組中提取隨機元素?
    如何從PHP中的數組中提取隨機元素?
    從陣列中的隨機選擇,可以輕鬆從數組中獲取隨機項目。考慮以下數組:; 從此數組中檢索一個隨機項目,利用array_rand( array_rand()函數從數組返回一個隨機鍵。通過將$項目數組索引使用此鍵,我們可以從數組中訪問一個隨機元素。這種方法為選擇隨機項目提供了一種直接且可靠的方法。
    程式設計 發佈於2025-04-20
  • 在所有瀏覽器中實現左對齊文本的斜線方法
    在所有瀏覽器中實現左對齊文本的斜線方法
    ] 在傾斜行上的文本對齊背景在傾斜行上實現左對齊的文本可能會構成挑戰,在nectera時尤其是挑戰。兼容性(返回IE9)。 通過引入一系列平方元素併計算其尺寸,我們可以創建一個有效的解決方案: .loop(@i) when (@i > 0){ .loop((@i - ...
    程式設計 發佈於2025-04-20
  • 在UTF8 MySQL表中正確將Latin1字符轉換為UTF8的方法
    在UTF8 MySQL表中正確將Latin1字符轉換為UTF8的方法
    在UTF8表中將latin1字符轉換為utf8 ,您遇到了一個問題,其中含義的字符(例如,“jáuòiñe”)在utf8 table tabled tablesset中被extect(例如,“致電。為了解決此問題,您正在嘗試使用“ mb_convert_encoding”和“ iconv”轉換受...
    程式設計 發佈於2025-04-20
  • 您如何在Laravel Blade模板中定義變量?
    您如何在Laravel Blade模板中定義變量?
    在Laravel Blade模板中使用Elegance 在blade模板中如何分配變量對於存儲以後使用的數據至關重要。在使用“ {{}}”分配變量的同時,它可能並不總是最優雅的解決方案。 幸運的是,Blade通過@php Directive提供了更優雅的方法: $ old_section =...
    程式設計 發佈於2025-04-20
  • 為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    mySQL錯誤#1089:錯誤的前綴鍵錯誤descript [#1089-不正確的前綴鍵在嘗試在表中創建一個prefix鍵時會出現。前綴鍵旨在索引字符串列的特定前綴長度長度,可以更快地搜索這些前綴。 了解prefix keys `這將在整個Movie_ID列上創建標準主鍵。主密鑰對於唯一識...
    程式設計 發佈於2025-04-20
  • 在Java中使用for-to-loop和迭代器進行收集遍歷之間是否存在性能差異?
    在Java中使用for-to-loop和迭代器進行收集遍歷之間是否存在性能差異?
    For Each Loop vs. Iterator: Efficiency in Collection TraversalIntroductionWhen traversing a collection in Java, the choice arises between using a for-...
    程式設計 發佈於2025-04-20
  • 在細胞編輯後,如何維護自定義的JTable細胞渲染?
    在細胞編輯後,如何維護自定義的JTable細胞渲染?
    在JTable中維護jtable單元格渲染後,在JTable中,在JTable中實現自定義單元格渲染和編輯功能可以增強用戶體驗。但是,至關重要的是要確保即使在編輯操作後也保留所需的格式。 在設置用於格式化“價格”列的“價格”列,用戶遇到的數字格式丟失的“價格”列的“價格”之後,問題在設置自定義單元...
    程式設計 發佈於2025-04-20
  • 為什麼儘管有效代碼,為什麼在PHP中捕獲輸入?
    為什麼儘管有效代碼,為什麼在PHP中捕獲輸入?
    在php ;?>" method="post">The intention is to capture the input from the text box and display it when the submit button is clicked.但是,輸出...
    程式設計 發佈於2025-04-20
  • 在JavaScript中如何並發運行異步操作並正確處理錯誤?
    在JavaScript中如何並發運行異步操作並正確處理錯誤?
    同意操作execution 在執行asynchronous操作時,相關的代碼段落會遇到一個問題,當執行asynchronous操作:此實現在啟動下一個操作之前依次等待每個操作的完成。要啟用並發執行,需要進行修改的方法。 第一個解決方案試圖通過獲得每個操作的承諾來解決此問題,然後單獨等待它們: c...
    程式設計 發佈於2025-04-20
  • 圖片在Chrome中為何仍有邊框? `border: none;`無效解決方案
    圖片在Chrome中為何仍有邊框? `border: none;`無效解決方案
    在chrome 在使用Chrome and IE9中的圖像時遇到的一個頻繁的問題是圍繞圖像的持續薄薄邊框,儘管指定了圖像,儘管指定了;和“邊境:無;”在CSS中。要解決此問題,請考慮以下方法: Chrome具有忽略“ border:none; none;”的已知錯誤,風格。要解決此問題,請使用以下...
    程式設計 發佈於2025-04-20
  • 為什麼不````''{margin:0; }`始終刪除CSS中的最高邊距?
    為什麼不````''{margin:0; }`始終刪除CSS中的最高邊距?
    在CSS 問題:不正確的代碼: 全球範圍將所有餘量重置為零,如提供的代碼所建議的,可能會導致意外的副作用。解決特定的保證金問題是更建議的。 例如,在提供的示例中,將以下代碼添加到CSS中,將解決餘量問題: body H1 { 保證金頂:-40px; } 此方法更精確,避免了由全局保證金重置...
    程式設計 發佈於2025-04-20

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3