Search code examples
mysqlbatch-filemysql-error-1045

How can I check the mysql connection for a user/password using batch/shell script


How can I check the mysql connection for a user/password using batch/shell script?

I've user name and password, and I need to authenticate whether they are correct or not, but how?

I tried this way:

  1. I've created a batch file "run.bat" with "mysql -u User--password=UserPassword < commands.sql"
  2. "commands.sql" file contains "\q"
  3. When I run the file "run.bat" the output is nothing when User/Password are correct and "ERROR 1045 (28000): Access denied for user ... " when User/Password are incorrect. Now can we capture this output, and decide whether the connection is successful or not, if yes how?

Regards


Solution

  • I found a solution as below:

    @echo OFF
    echo \q | mysql -u User --password=UserPassword 2>nul
    
    if "%ERRORLEVEL%" == "0" (
      echo CONNECTION SUCCESSFUL
    ) else (
      echo CONNECTION FAILED
    )