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

标签 mysql bash

我尝试通过名称中带有破折号的 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 -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 - 通过 bash 在数据库名称中使用破折号创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28881624/

相关文章:

php - 无法使用 php 使用 php 函数读取插入到 mysql 数据库中的行,就在函数被调用之后

bash:在命令行参数中添加注释

bash - 在 awk printf 中使用可变长度的提示

regex - 如何 grep 查找包含至少一次出现的多个范围的正则表达式

javascript - 在for循环javascript中显示唯一值

mysql2 : error on reading inital communication packets

mysql - 在 mySql 中找到类似的条目

java - jOOQ 将字符串转换为 boolean 值

git - 使用备用帐户在 GitHub 上共享项目

linux - 在 Gnome Scheduler 中运行 Bash 脚本时出现奇怪的 Bash 错误