限制最大备份数量 .bat执行文件,
winsdows设置计划任务 可设置为凌晨1:00 或者别的时间段 , 每天执行备份 或者 每周执行备份等
@echo off
::数据库名,贴着=写参数。不要留空格
set "database=db1_data"
set "user=root"
set "pswd=root"
set "url=127.0.0.1"
set "port=3306"
:: 获取日期信息
set "year=%date:~0,4%"
set "month=%date:~5,2%"
set "day=%date:~8,2%"
set "dformat=%year%_%month%_%day%"
:: 设置要清理的目录
set "dir_path=D:\mysql\backups\"
:: 设置备份存储路径
set "path=%dir_path%\%dformat%"
:: 最多保留的备份数量
set "max_backups=3"
:: 确保备份路径存在
if not exist "%path%" mkdir "%path%"
:: 创建数据库备份
"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqldump" --opt -u %user% --password=%pswd% -h %url% -P %port% %database% > "%path%\%database%_%dformat%.sql"
:: 确保目录存在
if not exist "%dir_path%\*" (
echo 目录不存在或为空: "%dir_path%"
goto end
)
setlocal enabledelayedexpansion
:: 删除旧目录
set /a index=1
for /f "delims=" %%i in ('dir "%dir_path%" /b /ad /o-d') do (
if !index! gtr %max_backups% (
rd /s /q "%dir_path%\%%i"
)
set /a index+=1
)
@echo on
::@pause
@exit