Make sure that Python is installed in your system and MySQL server has a database that you want to backup.
How to Automatically Backup MySQL Database Using Python?
Head towards any code editor to write the python code to automatically backup MySQL database. For this post, “Visual Studio Code” is being used:
Create a python file named “backup.py”:
Import these required libraries at the beginning of the python file:
import time
Enter your MySQL database credentials:
DB_USER = 'your_mysql_username'
DB_PASS = 'your_mysql_password'
DB_NAME = 'your_database_name'
Provide the backup directory, where the MySQL database backup should be saved. Make sure to replace the path according to your system, “D:\\MySQL_Data_backup_files” is the path for this post:
Enter the “date_format” to define the data format for the backup files:
Set the “BACKUP_INTERVAL”, to define the time after which a backup should automatically create:
Note: In this post, the backup interval is 20 seconds, you can set any, but it should be defined in seconds.
Type this piece of code to format the current time in the “date_format”:
current_time = time.strftime(date_format)
Define the backup file name:
Define the full path of the backup file by typing the following code:
Use the mysqldump command to create a backup file by providing the required parameters according to your MySQL database:
os.system(mysqldump_cmd)
To save space on the disk, compress the backup file using the gzip tool by typing:
os.system(gzip_cmd)
To remove the old backup files, use the find command and delete them. For this post, files that are old than “7” days will be deleted:
os.system(find_cmd)
Lastly, type this to wait for the backup interval:
Review your file and ensure everything is according to your system and MySQL database. Save the file by pressing “CTRL + S”:
Run the file by opening the terminal or the Command prompt in this directory and typing:
Head to the directory to confirm that backup files are created after each “20 Seconds” as it was the backup interval:
It is visible in the output that backup files are created automatically.
Conclusion
To automatically back up MySQL databases using Python. Create a python file, and provide MySQL database details, backup interval, date, and file name format. Use the mysqldump command to create backup files and gzip to compress them. Execute the file to start the backup process. This guide demonstrates the process of creating backup files of MySQL database automatically.