python实现Mysql自动备份与还原方法

一、自动备份:将以下代码保存为*.py批处理脚本,然后再添加Windows定时作业,如每天凌晨2点执行:

import subprocess
import os
import datetime

# 获取当前日期时间
now = datetime.datetime.now()
# 创建备份文件夹
backup_dir = os.path.join(os.getcwd(), "database_backup")
if not os.path.exists(backup_dir):
    os.makedirs(backup_dir)

def backup_database(host, username, password, database, backup_path):
    command = f"mysqldump -h {host} -u {username} -p{password} {database} > {backup_path}"
    subprocess.run(command, shell=True)

filename = os.path.join(backup_dir, "database_" + now.strftime("%Y%m%d%H%M%S") + ".sql")
backup_database("localhost", "username", "password", "database", filename)

print("backup finished")

说明:databasename 为数据库名 password为数据库密码,系统自动以当前日期时间备份至指定目录。

发表评论