fbpx

Python script to take MySQL Database Backup

Code

				
					import os
import subprocess

# Set the MySQL user and password
MYSQL_USER = "username"
MYSQL_PASSWORD = "password"

# Set the name of the database to be backed up
DATABASE_NAME = "database_name"

# Set the directory for the backup files
BACKUP_DIRECTORY = "/path/to/backup/directory"

# Set the current date and time
NOW = os.strftime("%Y-%m-%d-%H-%M-%S")

# Export the database to a SQL file
subprocess.run(
    [
        "mysqldump",
        "-u",
        MYSQL_USER,
        "-p" + MYSQL_PASSWORD,
        DATABASE_NAME,
        ">",
        BACKUP_DIRECTORY + "/" + DATABASE_NAME + "-" + NOW + ".sql",
    ]
)

# Compress the SQL file using gzip
subprocess.run(["gzip", BACKUP_DIRECTORY + "/" + DATABASE_NAME + "-" + NOW + ".sql"])

				
			

This script uses the mysqldump utility to export the database to a SQL file, and then uses gzip to compress the file. The SQL file is named using the current date and time, so each backup will have a unique filename. You can customize the script by modifying the variables at the top to match your MySQL login details and the name of the database you want to back up.

To use the script, save it to a file with a .py extension and run it using the python command:

				
					python [script_name.py]

				
			

It’s a good idea to schedule regular backups using a tool like cron so that you don’t have to remember to run the script manually. This will ensure that your MySQL databases are regularly backed up and protected against data loss.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories