642

I want to execute a text file containing SQL queries, in MySQL.

I tried to run source /Desktop/test.sql and received the error:

mysql> . \home\sivakumar\Desktop\test.sql ERROR: Failed to open file '\home\sivakumar\Desktop\test.sql', error: 2

Any idea on what I am doing wrong?

2

23 Answers 23

694

If you’re at the MySQL command line mysql> you have to declare the SQL file as source.

mysql> source \home\user\Desktop\test.sql;
12
  • 35
    For mysql 5.6.10 on Mac, no single quotes are needed for the file path.
    – RNA
    Commented Jul 13, 2013 at 0:39
  • 6
    for windows, using '/' instead of '\' worked correctly for me. I got errors when I originally used '/'. This is what worked for me...source C:/Users/macombers/Downloads/midcoast_db.sql; Commented Oct 3, 2014 at 15:09
  • 1
    Drop the quotes on ubuntu too (mysql Ver 14.14 debian-linux-gnu (x86_64) using EditLine wrapper)
    – Siddhartha
    Commented Apr 20, 2015 at 23:37
  • 1
    @kapil Relative to what? You’re inside MySQL at this point, so there is no relative I’m afraid. Commented Mar 11, 2017 at 0:23
  • 2
    @kapil I know this post is pretty old, but if you are in the folder your script is in before you start mysql, you don't need to type the full path.
    – Colby
    Commented Mar 3, 2019 at 3:44
302

You have quite a lot of options:

  • use the MySQL command line client: mysql -h hostname -u user database < path/to/test.sql
  • Install the MySQL GUI tools and open your SQL file, then execute it
  • Use phpmysql if the database is available via your webserver
4
  • 6
    What about the user's password (-p option)?
    – Amir Katz
    Commented Jan 22, 2018 at 16:15
  • 1
    @AmirKatz While the password can be given with the -p option, this is not recommended: Other users on the same host can use system tools like ps to read it in this case. Commented Jan 22, 2018 at 16:16
  • 8
    @EugenRieck -p without an argument prompts for the password to be entered on the next line
    – Bobby Jack
    Commented Nov 12, 2018 at 12:28
  • How do I keep mysql open after running the script?
    – user3310334
    Commented Apr 18, 2023 at 16:01
205

you can execute mysql statements that have been written in a text file using the following command:

mysql -u yourusername -p yourpassword yourdatabase < text_file

if your database has not been created yet, log into your mysql first using:

mysql -u yourusername -p yourpassword

then:

mysql>CREATE DATABASE a_new_database_name

then:

mysql -u yourusername -p yourpassword a_new_database_name < text_file

that should do it!

More info here: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html

3
  • 13
    on Windows: for the password I had to use quotation marks and NO space to make it work (the password itself did not contain any spaces or special chars): mysql -u yourusername -p"yourpassword"
    – TmTron
    Commented Sep 11, 2014 at 12:18
  • 2
    If you don't want your password to be on the prompt I believe the method outlined here will work: stackoverflow.com/questions/9293042/…
    – alex9311
    Commented Feb 4, 2016 at 9:32
  • What if i dont want to create the database, how to create automatically? I have over 30 databases ☹️ Commented Aug 26, 2022 at 19:38
95

My favorite option to do that will be:

 mysql --user="username" --database="databasename" --password="yourpassword" < "filepath"

I use it this way because when you string it with "" you avoiding wrong path and mistakes with spaces and - and probably more problems with chars that I did not encounter with.


With @elcuco comment I suggest using this command with [space] before so it tell bash to ignore saving it in history, this will work out of the box in most bash.

in case it still saving your command in history please view the following solutions:

Execute command without keeping it in history


extra security edit

Just in case you want to be extra safe you can use the following command and enter the password in the command line input:

mysql --user="username" --database="databasename" -p < "filepath"
9
  • 28
    I would not recommend passing the password to the command line, as it will be saved in the ~/.bash_history, and can be accessed by other programs trough /proc/.
    – elcuco
    Commented May 13, 2015 at 10:10
  • Excellent advice from @elcuco! Also, probably use another flag after -p (or have that be the last arg) so another parameter is not erroneously taken to be the intended password.
    – davernator
    Commented May 26, 2018 at 1:48
  • Please note that, command line arguments are still visible by other users. Example: for i in /proc/*/cmdline ; do echo $i; cat $i; done
    – elcuco
    Commented Jul 25, 2018 at 7:30
  • This is NOT recommencement as you expose your servers password to the console's history Commented Mar 4, 2019 at 9:05
  • @AlexiusDiakogiannis can you give me example how can you view the command from history when you execute it with [space] before the command?
    – talsibony
    Commented Mar 7, 2019 at 10:04
71

All the top answers are good. But just in case someone wants to run the query from a text file on a remote server AND save results to a file (instead of showing on console), you can do this:

mysql -u yourusername -p yourpassword yourdatabase < query_file > results_file

Hope this helps someone.

2
  • 14
    I think there should be no space between -p and the password
    – webNeat
    Commented Feb 21, 2016 at 21:50
  • If the purpose of writing to file is taking data dump, I guess SELECT ... INTO OUTFILE /path/to/file.csv is more efficient way. See options and syntax here - dev.mysql.com/doc/refman/5.7/en/select-into.html
    – Anis
    Commented Feb 21, 2018 at 6:43
40

I came here searching for this answer as well, and here is what I found works the best for me: Note I am using Ubuntu 16.x.x

  1. Access mysql using:

mysql -u <your_user> - p

  1. At the mysql prompt, enter:

source file_name.sql

Hope this helps.

5
  • 6
    Instead of launching the prompt, it might even be useful to just combine the two steps in a single command: mysql -u<user> -p -e 'source filename.sql'
    – junix
    Commented May 14, 2018 at 11:33
  • Thanks, @junix! The source option used this way is what I was looking for.
    – ManuelJE
    Commented Feb 19, 2019 at 16:24
  • @junix This solution combines best of both words i.e. not having to enter the interactive mode, and preserve the output formatting.
    – kqvanity
    Commented Mar 15, 2023 at 5:20
  • @junix how do you stay in interactive mode after that?
    – user3310334
    Commented Apr 18, 2023 at 16:02
  • @minseong You don't, as you don't start the client in interactive mode.
    – junix
    Commented Sep 4, 2023 at 6:14
31

Give the path of .sql file as:

source c:/dump/SQL/file_name.sql;

See In The Image:

1
  • Thanks a ton! this works even if your user does not have SUDO rights and on remote Amazon RDS
    – Volatil3
    Commented Dec 16, 2019 at 6:42
28

instead of redirection I would do the following

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

This will execute the file path-to-sql-file

1
  • 1
    It is truly amazing how stupid it is that there is no --file option for mysql... Commented Oct 23, 2023 at 6:00
23
mysql> source C:\Users\admin\Desktop\fn_Split.sql

Do not specify single quotes.

If the above command is not working, copy the file to c: drive and try again. as shown below,

mysql> source C:\fn_Split.sql
19

mysql -u your-username database-name < file.sql -p

17

Never is a good practice to pass the password argument directly from the command line, it is saved in the ~/.bash_history file and can be accessible from other applications.

Use this instead:

mysql -u user --host host --port 9999 database_name < /scripts/script.sql -p
Enter password:
17

So many ways to do it.

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

If you get errors from the command line, make sure you have previously run

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

This must be run from within the mysqld.exe directory, hence the CD.

Hope this is helpful and not just redundant.

1
  • 1
    thank you for this, option 3 worked for me. where the others before did not do so great.
    – Renier
    Commented Feb 14, 2022 at 7:51
12

From linux 14.04 to MySql 5.7, using cat command piped with mysql login:

cat /Desktop/test.sql | sudo mysql -uroot -p 

You can use this method for many MySQL commands to execute directly from Shell. Eg:

echo "USE my_db; SHOW tables;" | sudo mysql -uroot -p 

Make sure you separate your commands with semicolon (';').

I didn't see this approach in the answers above and thought it is a good contribution.

8

Very likely, you just need to change the slash/blackslash: from

 \home\sivakumar\Desktop\test.sql

to

 /home/sivakumar/Desktop/test.sql

So the command would be:

source /home/sivakumar/Desktop/test.sql
7

If you are trying this command :

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

You may get an error like this : if you have special characters, mainly '`'

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

So I would suggest to use a command like this :

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

This command will execute source /path/to/script.sql once connected to the server, which execute your script.

6

use the following from mysql command prompt-

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

Use no quotation. Even if the path contains space(' ') use no quotation at all.

4

Since mysql -u yourusername -p yourpassword yourdatabase < text_file did not work on a remote server (Amazon's EC2)...

Make sure that the Database is created first.

Then:

mysql --host=localhost --user=your_username --password=your_password your_database_name < pathTofilename.sql
3

For future reference, I've found this to work vs the aforementioned methods, under Windows in your msql console:

mysql>>source c://path_to_file//path_to_file//file_name.sql;

If your root drive isn't called "c" then just interchange with what your drive is called. First try backslashes, if they dont work, try the forward slash. If they also don't work, ensure you have your full file path, the .sql extension on the file name, and if your version insists on semi-colons, ensure it's there and try again.

1
  • Why the double slashes?
    – gwideman
    Commented Mar 9, 2023 at 4:49
3

In your terminal follow the steps below. Note replace my_user, my_database and file_name with your details.

mysql -u my_user -p

use my_database;

source file_name.sql
2

In powershell, when using > C:\backup\backup.sql we kept getting

The '<' operator is reserved for future use.

So if someone else is thrashing on this on a windows box and using cmd or powershell, this did it for us.

.\mysql.exe -u root -p -D db_prod -e "source C:\\backup\\yesterday.sql" 
1

I use Bash's Here Strings for an instant SQL execution:

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

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

1

If you are here LOOKING FOR A DRUPAL ENVIRONMENT

You can run with drush command on your project directory

drush sqlc
0

I had this error, and tried all the advice i could get to no avail.

Finally, the problem was that my folder had a space in the folder name which appearing as a forward-slash in the folder path, once i found and removed it, it worked fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.