在数据库名称中使用破折号通过 bash 创建数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28881624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating database via bash with dash in database-name
提问by Fuzzyma
I try to create a new Database via bash which has a dash in the name.
我尝试通过名称中带有破折号的 bash 创建一个新数据库。
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:
我玩了一会儿,发现即使名称中没有破折号,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
I am kinda confused. Whats wrong here?
我有点困惑。这里有什么问题吗?
PS: In phpmyadmin it works as expected when adding backticks
PS:在 phpmyadmin 中添加反引号时它按预期工作
回答by hek2mgl
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
否则,shell 会将反引号扩展为命令替换。检查这个: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
进一步注意,您不需要 echo 命令。您可以使用-e
mysql的命令行选项
回答by Alex K
Use with backslahes before backticks:
在反引号前与反斜杠一起使用:
mysql -uuser -ppw -e 'CREATE DATABASE IF NOT EXISTS \`db-name\` CHARACTER SET utf8 COLLATE utf8_general_ci'