【问题标题】:creating database via bash with dash in database-name通过 bash 在数据库名称中使用破折号创建数据库
【发布时间】:2015-05-07 01:04:50
【问题描述】:

我尝试通过名称中包含破折号的 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 中添加反引号时会按预期工作

【问题讨论】:

    标签: mysql bash


    【解决方案1】:

    您可以引用反引号或简单地使用单引号而不是命令周围的双引号:

    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命令行选项

    【讨论】:

    • 我不知道必须转义反引号。谢谢!
    • 有什么不对我没用的吗?命令---> mysql -uroot -pmysql -e 'CREATE DATABASE IF NOT EXISTS mifosplatform-tenants';
    • 很难说。如果它仍然不适合你,我建议打开一个问题
    【解决方案2】:

    在反引号前与反斜杠一起使用:

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

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 2013-01-02
      • 1970-01-01
      • 2012-10-05
      • 2016-04-13
      • 1970-01-01
      • 2020-01-19
      • 2014-07-03
      • 2019-02-28
      相关资源
      最近更新 更多