在批处理文件中使用整数计数器(还原MySQL数据库)

时间:2015-02-18 08:09:11

标签: mysql batch-file

我正在创建一个bat文件,以便从sql文件中自动恢复MySQL数据库。这是代码:

@ECHO OFF
REM author: Gideon Apollo Bardelas
SET attempt=0
SET MAX_ATTEMPT=4

@ECHO Deploying database on MySQL Server.
IF "%MYSQL_HOME%" == "" GOTO NOHOME

:YESHOME
SET mysql=%MYSQL_HOME%
@echo Running MySQL on the MYSQL_HOME...
GOTO :RUN_SCRIPT

:NOHOME
@ECHO.
@ECHO MySQL Server is not detected on the system.

:NOHOME_CONFIRM
set /p cho=Do you have a MySQL server installed (y/n)? %=%
if %cho%==Y goto :NOHOME_ASK
if %cho%==y goto :NOHOME_ASK
if %cho%==n goto :NOHOME_QUIT
if %cho%==N goto :NOHOME_QUIT

@echo Invalid choice.
goto :NOHOME_CONFIRM

    :NOHOME_ASK
    @ECHO.
    set /p temp_path=Please give your mysql directory (Q to terminate): %=%

        :NOHOME_PATH_VERIFY
        if %temp_path%==Q goto :END
        if %temp_path%==q goto :END
        IF EXIST %temp_path%\mysql.exe GOTO :NOHOME_PATH_ACCEPT
        GOTO :NOHOME_PATH_REJECT

        :NOHOME_PATH_ACCEPT
        SET mysql=%temp_path%
        @echo Running MySQL on the specified directory...
        GOTO :RUN_SCRIPT

        :NOHOME_PATH_REJECT
        @echo Cannot find mysql.exe in the specified directory.
        GOTO :NOHOME_ASK

    :NOHOME_QUIT
    @echo.
    @echo Please install first MySQL Server on your system to continue.
    GOTO :END

:RUN_SCRIPT
SET attempt=attempt+1
set /p username=MySQL username:  %=%
set /p password=MySQL password:  %=%
%mysql%\mysql -u %username% -p%password% mysql < schema.sql 1>NUL 2>NUL || GOTO :VALIDATE
GOTO :SUCCESS

    :VALIDATE
    if %attempt% EQU %MAX_ATTEMPT% (
        @ECHO.
        @ECHO You have reached maximum attempts to log in MySQL Server.
        GOTO :END
    ) ELSE GOTO :RUN_SCRIPT

    :SUCCESS
    @ECHO.
    @ECHO Finished deploying server.

:END
set /p cho=Press any key to quit. %=%

这已经奏效,直到我决定添加验证,当用户已经尝试三次登录MySQL时,它将终止批处理文件。问题是计数器不起作用。它将继续要求获得MySQL凭证,直到它收到正确的凭证。

我认为问题源于:VALIDATE子句。但我无法解决它。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您的错误在这里:

SET attempt=attempt+1

要使用set进行算术运算,您必须使用/a参数:

set /a attempt=%attempt%+1

您可以使用不%的变量和set /a

set /a attempt=attempt+1

或使用较短的表格:

set /a attempt+=1