数据库备份文件,例如保存为:dump_msyql.bat
REM 数据库备份
@echo offREM 激活延迟环境变量扩展,防止变量赋值丢失
setlocal enabledelayedexpansionREM 获取当天时间
set today=%date:~8,2%REM 大前天,当天-3天,小于10,前面补0
set /a daysAgo=%today%-3
if %daysAgo% lss 10 (set daysAgo=0%daysAgo%
)REM 获得年+月,例如:202306
set date=%date:~0,4%%date:~5,2%REM 今天要备份的目录
set today_dir=MySQL_Backup\%date%%today%REM 三天前要删除的备份目录
set ago_dir=MySQL_Backup\%date%%daysAgo%REM 创建今天备份的目录
if not exist %today_dir% (mkdir %today_dir%
)REM 静默删除3天前的备份
if exist %ago_dir% (rd /s /q %ago_dir%
)set dbs=MySQL_DbName1 MySQL_DbName2 MySQL_DbNameN
for %%i in (%dbs%) do (REM 将SQL脚本备份为压缩文件,需要安装 gzip 压缩程序并设置环境变量(大数据量推荐采用压缩)。mysqldump.exe -uroot -pDatabasePassword %%i | gzip.exe > %today_dir%\%%i.sql.gzREM 将SQL脚本备份为原始文件大小(小数据量推荐采用非压缩)。REM mysqldump.exe -uroot -pDatabasePassword %%i > %today_dir%\%%i.sql
)pause
数据库还原文件,例如保存为:restore_msyql.bat
REM 数据库还原
@echo off
setlocal enableDelayedExpansionset dbs=MySQL_DbName1 MySQL_DbName2 MySQL_DbNameN
for %%i in (%dbs%) do (REM mysql.exe -h127.0.0.1 -P3306 -uroot -pDatabasePassword -e "CREATE DATABASE IF NOT EXISTS `%%i` DEFAULT CHARACTER SET utf8 REM COLLATE utf8_general_ci;"REM 非解压缩还原。mysql.exe -h127.0.0.1 -P3306 -uroot -pDatabasePassword %%i < D:\MySQL_Backup\%%i.sqlREM 解压缩还原。REM gzip -d < D:\MySQL_Backup\%%i.sql.gz | mysql -uroot -pDatabasePassword %%i
)
pause