drop database if exists using mysqladmin in linux - mysql

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?

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

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

Related

Running a single mysql command with the 'runuser' command

For some strange reason, I can't find a way to make the runuser command work. I know it is possible to achieve this with sudo -u mysql mysql -e "$DB_SETUP but since I want to do this inside a script that already runs with sudo I find this not very pretty.
Here is what I am trying to do:
DB_SETUP="CREATE USER IF NOT EXISTS $DB_USER#$BASEURL IDENTIFIED BY '$DB_PASSWORD';CREATE DATABASE IF NOT EXISTS $DB_NAME;GRANT ALL PRIVILEGES ON $DB_NAME.* TO $DB_USER#$BASEURL IDENTIFIED BY '$DB_PASSWORD';FLUSH PRIVILEGES;"
sudo runuser -u mysql "mysql -e \"$DB_SETUP\"" # does not work
It gives me this error:
runuser: failed to execute mysql -e "CREATE USER IF NOT EXISTS db_user#baseurl IDENTIFIED BY 'db_password';CREATE DATABASE IF NOT EXISTS db_name;GRANT ALL PRIVILEGES ON db_name.* TO db_user#baseurl IDENTIFIED BY 'password';": No such file or directory
As commented above, I got it working with:
sudo runuser -u mysql mysql <<< $DB_SETUP
No quotation marks at all!

Escaping stripes from MySQL execute command

This should be so simple, but I cannot get it to work.
I am automating a release procedure on our server using bash (sh):
#!/bin/bash
oldDatabase=${1:-}
newDatabase=${2:-}
dbPassword=${3:-}
dbuser=${4:-}
if [ ! -z $oldDatabase ] ; then
mysql -u "$dbuser" "-p$dbPassword" -e "CREATE DATABASE IF NOT EXISTS $newDatabase"
mysqldump -u "$dbuser" "-p$dbPassword" $oldDatabase | mysql -u "$dbuser" "-p$dbPassword" $newDatabase;
else
echo "DB file: '$oldDatabase' not found/given!"
fi
This works great for database names like test_something, blabla, etc...
However, the current names of the database have a lot of stripes in it: rel-3-3-0.dev. I cannot get this to work, I keep getting a SQL error on the command. (ERROR 1064 in MySQL)
I guess the stripes in the query are not accepted by the command line MySQL variant, so I added backticks:
mysql -u "$dbuser" "-p$dbPassword" -e "CREATE DATABASE IF NOT EXISTS `$newDatabase`"
But this does not seem to work in either? (ERROR 1064 in MySQL)
Any way to get this working?
Never mind, it seems to work like this:
mysql -u "$dbuser" "-p$dbPassword" -e "CREATE DATABASE IF NOT EXISTS \`$newDatabase\`"

Run mysql commands in bash script without logging in or adding -u root to every command

I'm writing a bash script to do some db stuff. New to MySQL. I'm on Mac and have MySQL installed via homebrew.
Am using username "root" right now and there isn't a pw set. I included the pw syntax below just to help others out that may have a pw.
My goal is to have mysql commands be as "clean" as possible in my bash script
Not a hige deal, but would like to do this if possible.
Example
# If I can do it without logging in (*ideal)
mysql CREATE DATABASE dbname;
# Or by logging in with - mysql -u root -pPassword
CREATE DATABASE dbname;
# Instead of
mysql -u root -pPassword -e"CREATE DATABASE dbname";
Tried to simplify it. I have a handful of things I gotta do, so would rather keep my code cleaner if possible. I tried logging in with the bash script, but the script stopped once logged into MySQL and didn't run any commands.
Another option I was considering (but don't really like) would be just to keep username and pw string in a var and call it for every commmand like so
# Set the login string variable
login_details="-u root -p password -e"
# example command
mysql $login_details"CREATE DATABASE dbname";
So any ideas?
Write a new bash script file and run this file after putting all your commands into it. Don't forget to give right username and password in your bash script.
For bash script:
#!/bin/bash
mysql -u root -pSeCrEt << EOF
use mysql;
show tables;
EOF
If you want to run single mysql command.
mysql -u [user] -p[pass] -e "[mysql commands]"
Example:
mysql -h 192.168.1.10 -u root -pSeCrEt -e "show databases"
To execute multiple mysql commands:
mysql -u $user -p$passsword -Bse "command1;command2;....;commandn"
Note: -B is for batch, print results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file. Batch mode results in nontabular output format and escaping of special characters. -s is silent mode. Produce less output. -e is to execute the statement and quit

Calling MySQL Stored Procedure with escaped database name

I am using MySQL: 5.1.69
I have created stored procedures and called them many times. In this case, I appear to have hit a snag related to escape characters in the schema name.
our MySQL database / schema is named like this: www.company.com
Due to this, we must always escape the database name like this: `www.company.com`.table_name
I have created a procedure from within MySQLWorkbench
CREATE PROCEDURE usp_backfill_data
(p_var1 INT(11)
,p_var2 DATETIME)
BEGIN
/*do lots of work here*/
END
And from within MySQL Workbench I am able to call the procedure using:
use `www.company.com`;
CALL usp_backfill_data(5000, '2012-01-01');
Under these conditions the procedure works exactly as expected.
However, when I try to call the procedure from the command line:
%> mysql -uuser -ppassword -Dwww.company.com -e "CALL usp_backfill_data(5000, '2012-01-01');"
or when I try
%> mysql -uuser -ppassword -e "CALL \`www.company.com\`.usp_backfill_data(5000, '2012-01-01');"
or when I log into the mysql command line and use:
mysql> use `www.company.com`;
mysql> CALL usp_backfill_data(5000, '2012-01-01');
I always get the following error:
ERROR 1305 (42000) at line 1: PROCEDURE www.company.com.usp_backfill_data does not exist
I am hoping that there is something super obvious that I'm overlooking here.
Thank you very much for your time
To escape database name in command line use double quotes
$ mysql -uuser -ppassword -D"www.company.com" -e "CALL usp_backfill_data(5000, '2012-01-01');"
^ ^
Other two methods
$ mysql -uuser -ppassword -e "CALL \`www.company.com\`.usp_backfill_data(5000, '2012-01-01');"
and
$ mysql -uuser -ppassword
mysql> USE `www.company.com`;
Database changed
mysql> CALL usp_backfill_data(5000, '2012-01-01');
work for me just fine

How to delete mysql database through shell command

I use the pylons and sqlalchemy. I constantly update the schema files and delete and recreate the database so that new schema can be made.
Every time I do this by opening the MySql Query Browser and login and delete the database/schema.
How do I delete the MySQL db/schema thorough linux shell commands in Ubuntu Linux?
Try the following command:
mysqladmin -h[hostname/localhost] -u[username] -p[password] drop [database]
In general, you can pass any query to mysql from shell with -e option.
mysql -u username -p -D dbname -e "DROP DATABASE dbname"
If you are tired of typing your password, create a (chmod 600) file ~/.my.cnf, and put in it:
[client]
user = "you"
password = "your-password"
For the sake of conversation:
echo 'DROP DATABASE foo;' | mysql
Another suitable way:
$ mysql -u you -p
<enter password>
>>> DROP DATABASE foo;
No need for mysqladmin:
just use mysql command line
mysql -u [username] -p[password] -e 'drop database db-name;'
This will send the drop command although I wouldn't pass the password this way as it'll be exposed to other users of the system via ps aux
MySQL has discontinued drop database command from mysql client shell. Need to use mysqladmin to drop a database.
You can remove database directly as:
$ mysqladmin -h [host] -u [user] -p drop [database_name]
[Enter Password]
Do you really want to drop the 'hairfree' database [y/N]: y
[root#host]# mysqladmin -u root -p drop [DB]
Enter password:******