通过数据库名称中的破折号使用bash创建数据库

Fuz*_*yma 26 mysql bash

我尝试通过bash创建一个新的数据库,名称中有一个破折号.

那是我尝试过的:

echo "CREATE DATABASE IF NOT EXISTS db-name CHARACTER SET utf8 COLLATE utf8_general_ci" | mysql -uuser -ppw
Run Code Online (Sandbox Code Playgroud)

失败并出现以下错误:

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
Run Code Online (Sandbox Code Playgroud)

我添加了反引号:

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
Run Code Online (Sandbox Code Playgroud)

我玩了一下,发现即使名字中没有破折号,mysql也不喜欢反叛:

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
Run Code Online (Sandbox Code Playgroud)

我有点困惑.这里有什么不对?

PS:在phpmyadmin中,它在添加反引号时按预期工作

hek*_*mgl 32

要么引用反引号,要么只使用单引号而不是命令周围的双引号:

mysql -uuser -ppw -e 'CREATE DATABASE IF NOT EXISTS `db-name` CHARACTER SET utf8 COLLATE utf8_general_ci'
Run Code Online (Sandbox Code Playgroud)

否则shell会将反引号扩展为命令替换.请查看:http://tldp.org/LDP/abs/html/commandsub.html

另请注意,您不需要echo命令.您可以使用-emysql 的命令行选项