1

I'm trying to make a query from cmd that return 0 if database exists or any other number (for example 1), if it doesn't.

I make the query in this way:

"C:\mysql.exe" --host=localhost --user=root --password=pass --execute="SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DB_Name'"

If exists, it returns a table (and a exit code 0); if it doesn't, it returns nothing (and a exit code 0 too)

I use this on a Inno Setup installer like:

Exec(
  ExpandConstant('{tmp}\mysql.exe'),
  '--host='+eServer.text+' --user='+eUser.text+' --password='+ePass.text+
  ' --port='+ePort.text+
  ' --execute="SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '+
  ''''+eDBname.text+''''+'"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); 

if (ResultCode <> 0) then          
    MsgBox('Error when connecting to server', mbError, MB_OK);

So it returns me 0 even if the database doesn't exist.

3
  • 2
    What about adding --database "dbname" to the arguments? Untested for the moment, but that should fail if the db isn't there, otherwise the query will execute normally. Commented Aug 4, 2017 at 3:30
  • It Works, thank you so much, can you put your comment to select as answer? Commented Aug 4, 2017 at 15:12
  • I added your response before --execute and works Commented Aug 4, 2017 at 15:14

1 Answer 1

2

The mysql CLI supports a --database argument to set the default database before it runs any --execute queries. Setting this value to a nonexistent database (or one for which the user doesn't have the required access) causes the CLI to exit non-zero, because the specified database can't be set as the default.

Add the option in one of these formats:

--database "dbname"
--database="dbname"
-D "dbname"

https://dev.mysql.com/doc/refman/5.7/en/mysql-command-options.html#option_mysql_database

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.