search
HomeDatabaseMysql TutorialPython. Automating creation backups of MySQL database.

Python. Automating creation backups of MySQL database.

This script automates creating backups of MySQL databases, restoring them, and managing database and user creation on the destination MySQL server.

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:
This function checks if a database exists on a MySQL server. If the database does not exist, it creates it. It takes parameters such as the host, port, username, password, and database name to check or create.

check_and_create_user:
Like the database function, this function checks if a user exists on the MySQL server. If the user does not exist, it creates the user and grants privileges to a specific database. It also takes parameters such as the host, port, username, password, the name of the database, the new username, and the new password.

backup_mysql_database:
This function performs a backup of a MySQL database using mysqldump. It takes parameters such as the host, port, username, password, database name, and the path to save the backup file.

restore_mysql_database:
This function restores a MySQL database from a backup file. It takes parameters such as the host, port, username, password, database name, and the path to the backup file.

main:
This is the main function of the script. It sets up parameters for the source and target MySQL databases, including connection details, database names, and backup paths. It then performs checks to ensure that the source and target databases are different, creates the target database and user if they don’t exist, creates a backup of the source database, and finally restores the backup to the target database.

Additionally, the script uses the subprocess module to execute shell commands for MySQL operations (mysql, mysqldump) and performs error handling and output redirection (2>/dev/null) to suppress unnecessary output.

If you’re working with MySQL databases and want to create automation, this code will help you.

This code represents a good starting template for creating automation scripts for managing MySQL databases.

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$ 

ask_dima@yahoo.com

The above is the detailed content of Python. Automating creation backups of MySQL database.. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Describe MySQL asynchronous master-slave replication process.Describe MySQL asynchronous master-slave replication process.Apr 10, 2025 am 09:30 AM

MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

MySQL: Simple Concepts for Easy LearningMySQL: Simple Concepts for Easy LearningApr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL: A User-Friendly Introduction to DatabasesMySQL: A User-Friendly Introduction to DatabasesApr 10, 2025 am 09:27 AM

The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

How does the InnoDB Buffer Pool work and why is it crucial for performance?How does the InnoDB Buffer Pool work and why is it crucial for performance?Apr 09, 2025 am 12:12 AM

InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

MySQL: The Ease of Data Management for BeginnersMySQL: The Ease of Data Management for BeginnersApr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

When might a full table scan be faster than using an index in MySQL?When might a full table scan be faster than using an index in MySQL?Apr 09, 2025 am 12:05 AM

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use