In this article we are going to cover How to take MySQL Database Backups using Python Script | Automate MySQL Backups using Python
Prerequisite
- Ubuntu 24.04 LTS with sudo privileges
- Python3 Installed
Please follow below article install MySQL on Ubuntu
How to Install MySQL 8 on Ubuntu 20.04 LTS
MySQL Database Backups using Python Script
Create below python file
sudo nano dbbackup.py
Please find below Python script for MySQL database backup
#!/usr/local/bin/python3
import configparser
import os
import time
import getpass
HOST='localhost'
PORT='3306'
DB_USER='username'
DB_PASS='password'
# if using one database... ('database1',)
databases=('database1','database2','database3')
def get_dump(database):
filestamp = time.strftime('%Y-%m-%d-%I')
# D:/xampp/mysql/bin/mysqldump for xamp windows
os.popen("mysqldump -h %s -P %s -u %s -p%s %s > %s.sql" % (HOST,PORT,DB_USER,DB_PASS,database,database+"_"+filestamp))
print("\n|| Database dumped to "+database+"_"+filestamp+".sql || ")
if __name__=="__main__":
for database in databases:
get_dump(database)
Run the Python Script
python dbbackup.py or python3 dbbackup.py
Conclusion:
In this article we have covered How to take MySQL Database Backups using Python Script | Automate MySQL Backups using Python.