38

I try to create a new Database via bash which has a dash in the name.

Thats what I tried:

echo "CREATE DATABASE IF NOT EXISTS db-name CHARACTER SET utf8 COLLATE utf8_general_ci" | mysql -uuser -ppw

That fails with the following error:

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the 
right syntax to use near
'-name CHARACTER SET utf8 COLLATE utf8_general_ci' at line 1

I added backticks then:

echo "CREATE DATABASE IF NOT EXISTS `db-name` CHARACTER SET utf8 COLLATE utf8_general_ci" | mysql -uuser -ppw

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the 
right syntax to use near
'CHARACTER SET utf8 COLLATE utf8_general_ci' at line 1

I played around a bit and found out that mysql doesnt like backticks even without a dash in the name:

echo "CREATE DATABASE IF NOT EXISTS `dbname` CHARACTER SET utf8 COLLATE utf8_general_ci" | mysql -uuser -ppw

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the 
right syntax to use near
'CHARACTER SET utf8 COLLATE utf8_general_ci' at line 1

I am kinda confused. Whats wrong here?

PS: In phpmyadmin it works as expected when adding backticks

3 Answers 3

55

Either you quote the backticks or simply use single quotes instead double quotes around the command:

mysql -uuser -ppw -e 'CREATE DATABASE IF NOT EXISTS `db-name` CHARACTER SET utf8 COLLATE utf8_general_ci'

Otherwise the shell would expand the backticks to a command substitution. Check this: http://tldp.org/LDP/abs/html/commandsub.html

Further note that you don't need the echo command. You can use the -e commandline option of mysql

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

3 Comments

I didnt know that backticks have to be escaped. Thank you!
any things wrong it did not work for me ? Command ---> mysql -uroot -pmysql -e 'CREATE DATABASE IF NOT EXISTS mifosplatform-tenants';
Hard to say. I recommend opening a question if it still doesn't work for you
4

Use with backslahes before backticks:

mysql -uuser -ppw -e 'CREATE DATABASE IF NOT EXISTS \`db-name\` CHARACTER SET utf8 COLLATE utf8_general_ci'

Comments

0

The correct way is to add back-ticks around the database name, like you do it with field names for example. Single quotes will not work usually.

CREATE DATABASE `db-name`;

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.