Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Created March 14, 2011 14:50
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save sindresorhus/869240 to your computer and use it in GitHub Desktop.
Save sindresorhus/869240 to your computer and use it in GitHub Desktop.
Backup MySQL databases in separate gzipped sql files on Windows
@echo off
set dbUser=root
set dbPassword=password
set backupDir="C:\Documents and Settings\user\Desktop\backup\mysql"
set mysqldump="C:\Program Files\MySQL\MySQL Workbench 5.2 CE\mysqldump.exe"
set mysqlDataDir="C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.1\data"
set zip="C:\Program Files\7-Zip\7z.exe"
:: get date
for /F "tokens=2-4 delims=/ " %%i in ('date /t') do (
set mm=%%i
set dd=%%j
set yy=%%k
)
:: get time
for /F "tokens=5-8 delims=:. " %%i in ('echo.^| time ^| find "current" ') do (
set hh=%%i
set mm=%%j
)
set dirName=%yy%%mm%%dd%_%hh%%mm%
:: switch to the "data" folder
pushd %mysqlDataDir%
:: iterate over the folder structure in the "data" folder to get the databases
for /d %%f in (*) do (
if not exist %backupDir%\%dirName%\ (
mkdir %backupDir%\%dirName%
)
%mysqldump% --host="localhost" --user=%dbUser% --password=%dbPassword% --single-transaction --add-drop-table --databases %%f > %backupDir%\%dirName%\%%f.sql
%zip% a -tgzip %backupDir%\%dirName%\%%f.sql.gz %backupDir%\%dirName%\%%f.sql
del %backupDir%\%dirName%\%%f.sql
)
@vforbox
Copy link

vforbox commented Jan 4, 2017

:: get data and time
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set dirName=%date:~0,4%%date:~5,2%%date:~8,2%_%hour%-%time:~3,2%

@michael-milette
Copy link

michael-milette commented Jul 15, 2017

I have really enjoyed and made good use of this batch file. However it has a couple of issues:

Issue 1: The script won't backup databases that have a dash in the name of the database.
issue 2: The date won't format properly depending on the Windows date format settings.

I have resolved both of these issues in a similar batch file. Feel free to take a look:
https://github.com/michael-milette/batch/blob/master/mysqlbackup.cmd

It also has an option to just backup a single database instead of all of them.

@muriloinflue
Copy link

@michael-milette, loved your script. Saved me a ton of work! Do you have a script for restoring them too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment