WindowsStarter/base/Resources/mysql/template-initialize-and-start-mysql.bat
2025-08-26 15:43:47 +08:00

114 lines
2.9 KiB
Batchfile

@echo off
setlocal enabledelayedexpansion
chcp 65001 >nul
title Initialize And Startup MySQL
:: Check if running as administrator
net session >nul 2>&1
if %errorLevel% neq 0 (
echo Please run this script as Administrator!
pause
exit /b 1
)
:: Configuration parameters - modify these values according to your environment
set "MYSQL_HOME=%INSTALLPATH%"
set "MYSQL_BIN_PATH=%INSTALLPATH%\bin"
set "MYSQLD_PATH=%INSTALLPATH%\bin\mysqld.exe"
set "MY_INI_PATH=%INSTALLPATH%\my.ini"
set "SERVICE_NAME=x_database"
set "NEW_ROOT_PASSWORD=Root@2025"
set "DATA_DIR=%INSTALLPATH%\data"
:: 1. Check if mysqld.exe exists
if not exist "%MYSQLD_PATH%" (
echo Error: mysqld.exe not found at %MYSQLD_PATH%
pause
exit /b 1
)
:: 2. Check if my.ini exists
if not exist "%MY_INI_PATH%" (
echo Error: Configuration file my.ini not found at %MY_INI_PATH%
pause
exit /b 1
)
:: 3. Check if service already exists
sc query "%SERVICE_NAME%" >nul 2>&1
if %errorLevel% equ 0 (
echo Error: Service [%SERVICE_NAME%] already exists
pause
exit /b 1
)
echo "%DATA_DIR%"
if exist "%DATA_DIR%" (
set "isEmpty=true"
dir /a /b "%DATA_DIR%\*" 2>nul | findstr . >nul && set "isEmpty=false"
dir /ad /b "%DATA_DIR%\*" 2>nul | findstr . >nul && set "isEmpty=false"
if "!isEmpty!"=="false" (
echo Please empty the data directory first
pause
exit /b 1
) else (
echo Initialization conditions met
)
) else (
echo Initialization conditions met. Proceed with initialization?
choice /c yn /m "Enter your choice (Y/N): "
if errorlevel 2 (
echo User chose not to initialize. Exiting...
exit /b 0
) else (
echo Initializing directory...
mkdir "%DATA_DIR%"
if exist "%DATA_DIR%" (
echo Directory initialized successfully
) else (
echo Failed to initialize directory
pause
exit /b 1
)
)
)
:: 1. Initialize MySQL
echo [1/4] Initializing MySQL...
"%MYSQL_BIN_PATH%\mysqld" --defaults-file="%MY_INI_PATH%" --initialize-insecure --basedir="%MYSQL_HOME%" --datadir="%DATA_DIR%"
if errorlevel 1 (
echo Initialization failed
exit /b 1
)
:: 2. Register MySQL service
echo [2/4] Registering MySQL service [%SERVICE_NAME%]...
"%MYSQL_BIN_PATH%\mysqld" --install "%SERVICE_NAME%" --defaults-file="%MY_INI_PATH%"
if errorlevel 1 (
echo Service registration failed
exit /b 1
)
:: 3. Start MySQL service
echo [3/4] Starting MySQL service [%SERVICE_NAME%]...
net start "%SERVICE_NAME%"
if errorlevel 1 (
echo Service startup failed
exit /b 1
)
:: 4. Change root password
echo [4/4] Changing root password...
"%MYSQL_BIN_PATH%\mysql" -u root --skip-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '%NEW_ROOT_PASSWORD%'; FLUSH PRIVILEGES;"
if errorlevel 1 (
echo Password change failed
exit /b 1
)
echo MySQL successfully initialized and configured!
echo Service name: %SERVICE_NAME%
echo New root password: %NEW_ROOT_PASSWORD%
echo my.ini path: %MY_INI_PATH%
exit /b 0
endlocal