我想在MySQL中执行一个包含SQL查询的文本文件。

我试着运行source /Desktop/test。SQL和收到的错误:

mysql >。回家\ \ sivakumar桌面\ \测试。sql ERROR:无法打开文件 ' \ \ sivakumar \电脑\测试。Sql ',错误:2

你知道我哪里做错了吗?


当前回答

你可以使用下面的命令来执行已经写入文本文件的mysql语句:

mysql -u yourusername -p yourpassword yourdatabase < text_file

如果你的数据库还没有创建,首先登录到你的mysql使用:

mysql -u yourusername -p yourpassword

然后:

mysql>CREATE DATABASE a_new_database_name

然后:

mysql -u yourusername -p yourpassword a_new_database_name < text_file

这样就行了!

更多信息请访问:http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html

其他回答

我使用Bash的Here字符串进行即时SQL执行:

mysql -uroot -p <<<"select date(now())"

https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Here-Strings

使用下面的mysql命令提示符-

source \\home\\user\\Desktop\\test.sql;

不要使用报价。即使路径包含空格(' '),也不要使用引号。

你可以使用下面的命令来执行已经写入文本文件的mysql语句:

mysql -u yourusername -p yourpassword yourdatabase < text_file

如果你的数据库还没有创建,首先登录到你的mysql使用:

mysql -u yourusername -p yourpassword

然后:

mysql>CREATE DATABASE a_new_database_name

然后:

mysql -u yourusername -p yourpassword a_new_database_name < text_file

这样就行了!

更多信息请访问:http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html

如果你正在尝试这个命令:

mysql -u root -proot -D database < /path/to/script.sql

你可能会得到这样的错误:如果你有特殊字符,主要是' "

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 '/path/to/script.sql' at line 1

所以我建议使用这样的命令:

echo "source /path/to/script.sql" | mysql -u root -proot -D database

该命令将执行source /path/to/script。SQL一旦连接到服务器,将执行您的脚本。

而不是重定向,我会做以下事情

mysql -h <hostname> -u <username> --password=<password> -D <database> -e 'source <path-to-sql-file>'

这将执行文件path-to-sql-file