install and uninstall mysql server as windows service

Following are the handy batch scripts to install and uninstall a mySql server as windows service

Install

1) finds the available port to use 

2) creates options file

3) add the service

4) start the service

@echo off

set servicename=%1
set basedir=%2
set basedir=%basedir:”=%

REM Step 1) first find the free port available
set freePort=
set startPort=3306

:SEARCHPORT
netstat -o -n -a | find “LISTENING” | find “:%startPort% ” > NUL
if “%ERRORLEVEL%” equ “0” (
rem echo port unavailable %startPort%
set /a startPort +=1
GOTO :SEARCHPORT
) ELSE (
rem echo port available %startPort%
set freePort=%startPort%
GOTO :FOUNDPORT
)

:FOUNDPORT
rem echo free %freePort%

REM Step 2) write mysql config file
set configFileName=my_%DATE:/=-%@%TIME::=-%.ini
rem set configFileName=my.txt
rem echo %configFileName%

set configFileDir=%basedir%\config
IF EXIST “%configFileDir%” GOTO CONFIGDIREXIST
mkdir “%configFileDir%”
:CONFIGDIREXIST

set configFilePath=%configFileDir%\%configFileName%

echo ^[mysqld^] >> “%configFilePath%”
echo port = %freePort% >> “%configFilePath%”
echo basedir = %basedir% >> “%configFilePath%”
echo datadir = %basedir%\data >> “%configFilePath%”

REM Step 3) Add mysql service

“%basedir%\bin\mysqld” –install %servicename% –defaults-file=”%configFilePath%”
if %errorlevel% neq 0 exit /b %errorlevel%

REM Step 4) start mysql service
net start %servicename%
if %errorlevel% neq 0 exit /b %errorlevel%

 

Uninstall

1) stops the service

2) removes the service

 

@echo off

set servicename=%1

REM Step 1) stop mysql service
sc query %servicename% | find “RUNNING” > NUL
if “%ERRORLEVEL%” equ “0” (
rem echo service running
net stop %servicename%
if %errorlevel% neq 0 exit /b %errorlevel%
)

REM Step 2) remove mysql service

“%basedir%\bin\mysqld” –remove %servicename%
if %errorlevel% neq 0 exit /b %errorlevel%