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

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

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

你知道我哪里做错了吗?


当前回答

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

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一旦连接到服务器,将执行您的脚本。

其他回答

如果您正在寻找DRUPAL环境

您可以在项目目录上使用drush命令运行

drush sqlc

很可能,你只需要改变斜杠/黑斜杠: 从

 \home\sivakumar\Desktop\test.sql

to

 /home/sivakumar/Desktop/test.sql

因此,命令将是:

source /home/sivakumar/Desktop/test.sql

有很多种方法。

From Workbench: File > Run SQL Script -- then follow prompts

From Windows Command Line:
   Option 1: mysql -u usr -p
             mysql> source file_path.sql
   Option 2: mysql -u usr -p '-e source file_path.sql'
   Option 3: mysql -u usr -p < file_path.sql
   Option 4: put multiple 'source' statements inside of file_path.sql (I do this to drop and recreate schemas/databases which requires multiple files to be run)
             mysql -u usr -p < file_path.sql

如果从命令行得到错误,请确保之前运行过

cd {!!>>mysqld.exe home directory here<<!!}
mysqld.exe --initialize 

这必须在mysqld.exe目录中运行,也就是CD。

希望这是有用的,而不是多余的。

你可以使用下面的命令来执行已经写入文本文件的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 --user="username" --database="databasename" --password="yourpassword" < "filepath"

我这样使用它是因为当你用""来串的时候,你可以避免错误的路径和空格的错误,而且可能还有更多我没有遇到过的字符问题。


对于@elcuco注释,我建议在使用此命令之前使用[空格],这样它就会告诉bash忽略在历史中保存它,这将在大多数bash中开箱工作。

如果您的命令仍然保存在历史记录中,请查看以下解决方案:

执行命令时不保留历史记录


额外的安全编辑

如果你想要更加安全,你可以使用以下命令并在命令行输入输入密码:

mysql --user="username" --database="databasename" -p < "filepath"