如何在 MySQL 中使用命令行导入 SQL 文件?

我有一个从 phpMyAdmin 导出的 .sql 文件。 我想使用命令行将其导入不同的服务器。

我安装了 Windows Server 2008 R2。 我把.sql文件放在C盘,我试了一下这个命令

database_name < 文件.sql

它不起作用。 我收到语法错误。

  • 如何才能顺利导入此文件?
  • 我需要先创建一个数据库吗?

Easiest way to import into your schema:

Login to mysql and issue below mention commands.

mysql> use your_db_name;

mysql> source /opt/file.sql;

</div>

We can use this command to import SQL from the command line:

mysql -u username -p password db_name < file.sql

For example, if the username is root and password is password. And you have a database name as bank and the SQL file is bank.sql. Then, simply do like this:

mysql -u root -p password bank < bank.sql

Remember where your SQL file is. If your SQL file is in the Desktop folder/directory then go the desktop directory and enter the command like this:

cd ~/Desktop
mysql -u root -p password bank < bank.sql

And if you are in the Project directory and your SQL file is in the Desktop directory. If you want to access it from the Project directory then you can do like this:

cd ~/Project
mysql -u root -p password bank < ~/Desktop/bank.sql

For exporting a database:

mysqldump -u username -p database_name > file.sql

For importing a database:

mysql -u username -p database_name < file.sql
</div>

To import a database, use the following command.

mysql> create new_database;
mysql> use new_database;
mysql> source (Here you need to import the path of the SQL file);

E.g.:
mysql> source E:/test/dump.sql;

You need to use forward slashes (/) even on Windows, e.g., E:/test/dump.sql instead of E:\test\dump.sql

Or double backslashes (\\) because of escaping, i.e., E:\\test\\dump.sql

For importing multiple SQL files at one time, use this:

# Unix-based solution
for i in *.sql ; do mysql -u root -pPassword DataBase < $i ; done

For simple importing:

# Unix-based solution
mysql -u root -pPassword DataBase < data.sql

For WAMP:

REM mysqlVersion - replace with your own version
C:\wamp\bin\mysql\mysqlVersion\bin\mysql.exe -u root -pPassword DataBase < data.sql

For XAMPP:

C:\xampp\mysql\bin\mysql -u root -pPassword DataBase < data.sql