MySQL Database Backups using Python Script

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.

Python for Cloud, DevOps, Platform and SRE

FOSS TechNix

FOSS TechNix (Free,Open Source Software's and Technology Nix*) founded in 2019 is a community platform where you can find How-to Guides, articles for DevOps Tools,Linux and Databases.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap