How to run SQL statements from a text file

Tyler Tyler (258)
0

You may find that you need to execute SQL statements that exist in a .sql file. There are a few different ways to do this depending on what you want to accomplish and how to sql file is written. Read on to understand which way is right for you.

Posted in these interests:

mysql
PRIMARY
9 subscribers

If you didn't write the sql file yourself, make sure you know what is in the file and how it's constructed. You should know if the file is attempting to create a database or if the file assumed that the database already exists. In general you can run:

shell> mysql db_name < text_file
And this will execute the statements in your text_file using the database db_name. If your text file beings with USE db_name or creates a database, you won't need to specify the database. You can simply run:
shell> mysql < text_file

After logging into the mysql shell you can also execute the statements by running the source command:

mysql> source file_name