Mysql automatic backup and cleanup (Windows)

Mysql automatic backup and cleanup (Windows)

MySQL installed in Windows can be automatically backed up and cleaned through the bat backup cleaning script and Windows scheduled tasks.

1 Script

@echo off

:: 数据库IP
set host=127.0.0.1
:: 数据库端口号
set port=3306
:: 用户名
set user=root
:: 密码
set pass=root 

:: 要备份的数据库名称
set dbname=test
:: 设置备份文件放置的路径
set backup_dir=E:\mysql-bak\test
:: 备份日志
set logfile=%backup_dir%\%dbname%-log.txt
:: 备份保留天数
set backupDays=30

:: 如果文件夹不存在则创建
if not exist %backup_dir% md %backup_dir%

:: 获取当天的日期格式
set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set backup_date=%date:~3,4%%date:~8,2%%date:~11,2%%time:~0,2%%time:~3,2%%time:~6,2%

echo =========== %backup_date%  %dbname% =========== >> %logfile%

:: 设置备份文件的路径
set backupfile=%backup_dir%\%dbname%_backup_%backup_date%.sql

echo 备份文件名称为:%backupfile% >> %logfile%

echo 使用mysqldump对指定的MySql进行备份 >> %logfile%

mysqldump -h%host% -P%port% -u%user% -p%pass% -c --add-drop-table %dbname% > %backupfile%
 
echo 数据备份完成 >> %logfile%

echo 查询过期文件并删除 >> %logfile%

:: 打印符合条件的文件到日志
forfiles /p %backup_dir% /s /m %dbname%_backup_.* /d -%backupDays% /c "cmd /c echo @file" >> %logfile%
:: 清理过期文件
forfiles /p %backup_dir% /s /m %dbname%_backup_*.sql /d -%backupDays% /c "cmd /c del @file /f"

echo 删除完成 >> %logfile%

2 Create a scheduled task

Open [Control Panel] > [Administrative Tools] > [Task Scheduler] or directly search for Task Scheduler and select [Operation] > [Create Basic Task]
Insert image description here

Set the scheduled task name:
Insert image description here

The trigger defaults to "every day" (depending on actual conditions):
Insert image description here

Set the scheduled task start date and execution time:
Insert image description here

Select "Start Program":
Insert image description here

Select the script to perform the backup:
Insert image description here

After confirming that the information is correct, click Finish.
Insert image description here

You can manually right-click the task and execute it immediately to verify whether there are any problems with the script and check whether there are problems with the backup file after execution. To be on the safe side, you can also import the backed up SQL into the database and verify whether there are any problems with the backed up SQL.

Guess you like

Origin blog.csdn.net/weixin_46505978/article/details/130699788