How to take backups of MySQL databases using Python?

Backing up MySQL databases is crucial for data protection. Python provides several approaches using the subprocess module to execute the mysqldump command-line utility for creating reliable database backups.

Using subprocess Module

The subprocess module allows you to execute system commands from Python. We can use it to run mysqldump and create database backups ?

import subprocess

# Define database connection details
host = "localhost"
user = "username"
password = "password"
database = "database_name"
backup_file = "backup.sql"

# Execute the mysqldump command
command = f"mysqldump -h{host} -u{user} -p{password} {database} > {backup_file}"
subprocess.run(command, shell=True)

Replace the placeholders with your actual MySQL connection credentials.

Using pymysql with subprocess

The pymysql library provides a Python interface to MySQL. You can combine it with subprocess for more robust connection handling ?

import pymysql
import subprocess

# Define database connection details
host = "localhost"
user = "username"
password = "password"
database = "database_name"
backup_file = "backup.sql"

try:
    # Test connection with the MySQL database
    connection = pymysql.connect(host=host, user=user, password=password, database=database)
    
    # Execute the mysqldump command
    command = f"mysqldump -h{host} -u{user} -p{password} {database} > {backup_file}"
    subprocess.run(command, shell=True)
    
    # Close the database connection
    connection.close()
    print("Backup completed successfully.")
    
except pymysql.Error as e:
    print(f"Database connection failed: {e}")

Subprocess with Return Code Verification

You can check the return code to verify if the backup operation was successful ?

import subprocess

# Define database connection details
host = "localhost"
user = "username"
password = "password"
database = "database_name"
backup_file = "backup.sql"

# Execute the mysqldump command
command = f"mysqldump -h{host} -u{user} -p{password} {database}"
process = subprocess.run(command, shell=True, capture_output=True, text=True)

# Check status based on the return code
if process.returncode == 0:
    print("Database backup completed successfully.")
    # Write output to file
    with open(backup_file, 'w') as f:
        f.write(process.stdout)
else:
    print(f"Database backup failed with return code {process.returncode}.")
    print(f"Error: {process.stderr}")
Database backup completed successfully.

Secure Backup Function

Here's a complete function that handles backup with error checking ?

import subprocess
import os
from datetime import datetime

def backup_mysql_database(host, user, password, database, backup_dir="backups"):
    # Create backup directory if it doesn't exist
    if not os.path.exists(backup_dir):
        os.makedirs(backup_dir)
    
    # Generate timestamp for backup file
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_file = f"{backup_dir}/{database}_backup_{timestamp}.sql"
    
    # Construct mysqldump command
    command = [
        "mysqldump",
        f"-h{host}",
        f"-u{user}",
        f"-p{password}",
        database
    ]
    
    try:
        # Execute backup
        with open(backup_file, 'w') as f:
            process = subprocess.run(command, stdout=f, stderr=subprocess.PIPE, text=True)
        
        if process.returncode == 0:
            print(f"Backup successful: {backup_file}")
            return backup_file
        else:
            print(f"Backup failed: {process.stderr}")
            return None
            
    except Exception as e:
        print(f"Error during backup: {e}")
        return None

# Example usage
backup_file = backup_mysql_database("localhost", "username", "password", "test_db")
Backup successful: backups/test_db_backup_20231201_143022.sql

Security Considerations

When creating database backups, consider these security practices:

  • Secure Storage: Store backup files in encrypted locations
  • Environment Variables: Use environment variables for credentials instead of hardcoding
  • File Permissions: Set appropriate file permissions on backup files
  • Regular Testing: Test backup restoration periodically

Conclusion

Python's subprocess module provides effective ways to create MySQL database backups using mysqldump. Always verify return codes and implement proper error handling for reliable backup operations.

Updated on: 2026-03-27T07:23:41+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements