How to use script files with MySQL

How to use script files with MySQL


Use of the MySQL client can be improved at times by using script files. These files are normal text files with a .sql file extension. They can provide speed, reuse, and edibility improvements over the command line mysql client.


A mysql


Script files contain any MySQL client-readable commands that could be directly invoked on the interactive client. Each statement can be separated by a line break, and terminated by semicolons (;). Script files can be used in two different ways. Within the interactive mysql client, script files can be called as any other MySQL client command would be invoked:

SOURCE filename.sql;

This script file was invoked using its relative path. For instance, if you invoked the mysql command line client from C:/Users/User/Desktop and the .sql file is located at C:/Users/User/Desktop, then the path is unnecessary, only the file name is needed. However, if you invoked the mysql client from C:/Users/User, you could locate the file by either using the relative path, or the full path:

SOURCE Desktop/filename.sql;

or the full path:

SOURCE C:/Users/User/Desktop/filename.sql;

The second approach to invoking the script file, is to invoke it from the commandine, using the mysql client but before the client is initiated with a database connection:

mysql -u root -p < C:\Users\User\Desktop\filename.sql

If the script file contains errors, the statements following the error will not be executed. To continue after the error, you can add either of the following to force continued execution:

mysql -u root -p < C:\Users\User\Desktop\filename.sql -f


mysql -u root -p < C:\Users\User\Desktop\filename.sql --force

Within the script file itself, you can include any MySQL client-interpretable statements, such as:


You can also include SOURCE commands inside the script file. This will call other script files for execution. Adding SOURCE calls to the script file performing the call should be avoided.