我尝试通过名称中带有破折号的 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/