我尝试通过bash创建一个新的数据库,其名称中包含短划线。
这就是我的尝试:
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
'-name CHARACTER SET utf8 COLLATE utf8_general_ci' at line 1
然后我添加了反引号:
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
我玩了一下,发现即使名字中没有破折号,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
我有点困惑。这有什么不对吗?
PS:在phpmyadmin中,它在添加反引号时按预期工作
答案 0 :(得分:31)
要么引用反引号,要么只使用单引号而不是命令的双引号:
mysql -uuser -ppw -e 'CREATE DATABASE IF NOT EXISTS `db-name` CHARACTER SET utf8 COLLATE utf8_general_ci'
否则shell会将反引号扩展为命令替换。检查一下:http://tldp.org/LDP/abs/html/commandsub.html
进一步注意,您不需要echo命令。您可以使用mysql的-e
命令行选项
答案 1 :(得分:0)
在反推之前使用后挡板:
mysql -uuser -ppw -e 'CREATE DATABASE IF NOT EXISTS \`db-name\` CHARACTER SET utf8 COLLATE utf8_general_ci'