Ensure that Python is put in in your system and MySQL server has a database that you just need to backup.
The best way to Mechanically Backup MySQL Database Utilizing Python?
Head in the direction of any code editor to write down the python code to routinely backup MySQL database. For this publish, “Visible Studio Code” is getting used:
Create a python file named “backup.py”:
Import these required libraries at the start of the python file:
Enter your MySQL database credentials:
DB_USER = ‘your_mysql_username’
DB_PASS = ‘your_mysql_password’
DB_NAME = ‘your_database_name’
Present the backup listing, the place the MySQL database backup must be saved. Be sure to exchange the trail in line with your system, “D:MySQL_Data_backup_files” is the trail for this publish:
BACKUP_DIR = ‘D:MySQL_Data_backup_files’
Enter the “date_format” to outline the information format for the backup recordsdata:
date_format = ‘%Y-%m-%d_percentH-%M-%S’
Set the “BACKUP_INTERVAL”, to outline the time after which a backup ought to routinely create:
Observe: On this publish, the backup interval is 20 seconds, you possibly can set any, nevertheless it must be outlined in seconds.
Sort this piece of code to format the present time within the “date_format”:
current_time = time.strftime(date_format)
Outline the backup file title:
backup_file = f‘{DB_NAME}-{current_time}.sql’
Outline the total path of the backup file by typing the next code:
backup_file_path = os.path.be a part of(BACKUP_DIR, backup_file)
Use the mysqldump command to create a backup file by offering the required parameters in line with your MySQL database:
os.system(mysqldump_cmd)
To save lots of area on the disk, compress the backup file utilizing the gzip software by typing:
os.system(gzip_cmd)
To take away the previous backup recordsdata, use the discover command and delete them. For this publish, recordsdata which are previous than “7” days will probably be deleted:
os.system(find_cmd)
Lastly, sort this to attend for the backup interval:
time.sleep(BACKUP_INTERVAL)
Overview your file and guarantee every thing is in line with your system and MySQL database. Save the file by urgent “CTRL + S”:
Run the file by opening the terminal or the Command immediate on this listing and typing:
Head to the listing to substantiate that backup recordsdata are created after every “20 Seconds” because it was the backup interval:
It’s seen within the output that backup recordsdata are created routinely.
Conclusion
To routinely again up MySQL databases utilizing Python. Create a python file, and supply MySQL database particulars, backup interval, date, and file title format. Use the mysqldump command to create backup recordsdata and gzip to compress them. Execute the file to begin the backup course of. This information demonstrates the method of making backup recordsdata of MySQL database routinely.