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

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

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

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]刪除
最新教學 更多>
  • 如何將來自三個MySQL表的數據組合到新表中?
    如何將來自三個MySQL表的數據組合到新表中?
    mysql:從三個表和列的新表創建新表 答案:為了實現這一目標,您可以利用一個3-way Join。 選擇p。 *,d.content作為年齡 來自人為p的人 加入d.person_id = p.id上的d的詳細信息 加入T.Id = d.detail_id的分類法 其中t.taxonomy ...
    程式設計 發佈於2025-03-26
  • 如何從PHP中的數組中提取隨機元素?
    如何從PHP中的數組中提取隨機元素?
    從陣列中的隨機選擇,可以輕鬆從數組中獲取隨機項目。考慮以下數組:; 從此數組中檢索一個隨機項目,利用array_rand( array_rand()函數從數組返回一個隨機鍵。通過將$項目數組索引使用此鍵,我們可以從數組中訪問一個隨機元素。這種方法為選擇隨機項目提供了一種直接且可靠的方法。
    程式設計 發佈於2025-03-26
  • 如何使用不同數量列的聯合數據庫表?
    如何使用不同數量列的聯合數據庫表?
    合併列數不同的表 當嘗試合併列數不同的數據庫表時,可能會遇到挑戰。一種直接的方法是在列數較少的表中,為缺失的列追加空值。 例如,考慮兩個表,表 A 和表 B,其中表 A 的列數多於表 B。為了合併這些表,同時處理表 B 中缺失的列,請按照以下步驟操作: 確定表 B 中缺失的列,並將它們添加到表的...
    程式設計 發佈於2025-03-26
  • 如何有效地選擇熊貓數據框中的列?
    如何有效地選擇熊貓數據框中的列?
    在處理數據操作任務時,在Pandas DataFrames 中選擇列時,選擇特定列的必要條件是必要的。在Pandas中,選擇列的各種選項。 選項1:使用列名 如果已知列索引,請使用ILOC函數選擇它們。請注意,python索引基於零。 df1 = df.iloc [:,0:2]#使用索引0和1 ...
    程式設計 發佈於2025-03-26
  • 如何在鼠標單擊時編程選擇DIV中的所有文本?
    如何在鼠標單擊時編程選擇DIV中的所有文本?
    在鼠標上選擇div文本單擊帶有文本內容,用戶如何使用單個鼠標單擊單擊div中的整個文本?這允許用戶輕鬆拖放所選的文本或直接複製它。 在單個鼠標上單擊的div元素中選擇文本,您可以使用以下Javascript函數: function selecttext(canduterid){ if(d...
    程式設計 發佈於2025-03-26
  • 如何檢查對像是否具有Python中的特定屬性?
    如何檢查對像是否具有Python中的特定屬性?
    方法來確定對象屬性存在尋求一種方法來驗證對像中特定屬性的存在。考慮以下示例,其中嘗試訪問不確定屬性會引起錯誤: >>> a = someClass() >>> A.property Trackback(最近的最新電話): 文件“ ”,第1行, AttributeError: SomeClass...
    程式設計 發佈於2025-03-26
  • 如何在GO編譯器中自定義編譯優化?
    如何在GO編譯器中自定義編譯優化?
    在GO編譯器中自定義編譯優化 GO中的默認編譯過程遵循特定的優化策略。 However, users may need to adjust these optimizations for specific requirements.Optimization Control in Go Compi...
    程式設計 發佈於2025-03-26
  • 哪種方法更有效地用於點 - 填點檢測:射線跟踪或matplotlib \的路徑contains_points?
    哪種方法更有效地用於點 - 填點檢測:射線跟踪或matplotlib \的路徑contains_points?
    在Python Matplotlib's path.contains_points FunctionMatplotlib's path.contains_points function employs a path object to represent the polygon.它...
    程式設計 發佈於2025-03-26
  • 如何使用組在MySQL中旋轉數據?
    如何使用組在MySQL中旋轉數據?
    在關係數據庫中使用mySQL組使用mySQL組進行查詢結果,在關係數據庫中使用MySQL組,轉移數據的數據是指重新排列的行和列的重排以增強數據可視化。在這裡,我們面對一個共同的挑戰:使用組的組將數據從基於行的基於列的轉換為基於列。 Let's consider the following ...
    程式設計 發佈於2025-03-26
  • 如何將PANDAS DataFrame列轉換為DateTime格式並按日期過濾?
    如何將PANDAS DataFrame列轉換為DateTime格式並按日期過濾?
    Transform Pandas DataFrame Column to DateTime FormatScenario:Data within a Pandas DataFrame often exists in various formats, including strings.使用時間數據時...
    程式設計 發佈於2025-03-26
  • 如何使用FormData()處理多個文件上傳?
    如何使用FormData()處理多個文件上傳?
    )處理多個文件輸入時,通常需要處理多個文件上傳時,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    程式設計 發佈於2025-03-26
  • Java是否允許多種返回類型:仔細研究通用方法?
    Java是否允許多種返回類型:仔細研究通用方法?
    在Java中的多個返回類型:一種誤解類型:在Java編程中揭示,在Java編程中,Peculiar方法簽名可能會出現,可能會出現,使開發人員陷入困境,使開發人員陷入困境。 getResult(string s); ,其中foo是自定義類。該方法聲明似乎擁有兩種返回類型:列表和E。但這確實是如此嗎...
    程式設計 發佈於2025-03-26
  • 為什麼使用固定定位時,為什麼具有100%網格板柱的網格超越身體?
    為什麼使用固定定位時,為什麼具有100%網格板柱的網格超越身體?
    網格超過身體,用100%grid-template-columns 為什麼在grid-template-colms中具有100%的顯示器,當位置設置為設置的位置時,grid-template-colly修復了? 問題: 考慮以下CSS和html: class =“ snippet-code”> ...
    程式設計 發佈於2025-03-26
  • 如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    使用http request 上傳文件上傳到http server,同時也提交其他參數,java.net.net.urlconnection and Multipart/form-data Encoding是普遍的。 Here's a breakdown of the process:Mu...
    程式設計 發佈於2025-03-26
  • 如何在JavaScript對像中動態設置鍵?
    如何在JavaScript對像中動態設置鍵?
    在嘗試為JavaScript對象創建動態鍵時,如何使用此Syntax jsObj['key' i] = 'example' 1;不工作。正確的方法採用方括號: jsobj ['key''i] ='example'1; 在JavaScript中,數組是一...
    程式設計 發佈於2025-03-26

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

Copyright© 2022 湘ICP备2022001581号-3