-1

I am looking for a command to drop a database if exists from mysql. I want to execute the command in terminal and not using mysql query. Using here answer I found that I can drop database from terminal using

mysqladmin -h[hostname/localhost] -u[username] -p[password] drop [database]

How do I do the same thing using if-exists condition?

1
  • And where were you thinking of coding this IF statement? Commented Dec 31, 2019 at 18:10

2 Answers 2

1

There is no option for mysqladmin to add "IF EXISTS" to its drop database. It is hard-coded to accept a name of a database only, not any other syntax.

Here is line of code that formats the DROP DATABASE statement in the mysqladmin client:

sprintf(name_buff, "drop database `%.*s`", FN_REFLEN, db);

But you may not need IF EXISTS. Just try to drop the database. If it doesn't exist, the client will print an error, but the effect is the same.

Here's a demo I just ran in my shell:

$ mysqladmin -f drop test2
mysqladmin: DROP DATABASE test2 failed;
error: 'Can't drop database 'test2'; database doesn't exist'

The client will exit with status of 1. If you don't like that (like if you're running in a shell script with set -e in effect), you can suppress the exit status:

mysqladmin -f drop test2 || true

If you don't like to see the error message, you can redirect it:

mysqladmin -f drop test2 2>/dev/null || true
Sign up to request clarification or add additional context in comments.

Comments

0

Did you try to use 'e' argument, like : mysql -u root -p somedb -e "select * from mytable" ?

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.