SQLite provides us with the ability to run scripts directly from a file. This can be especially useful when you have a large script (such as creating a bunch of database tables and inserting data into those tables).
Below are five ways to run SQL scripts directly from a file in SQLite.
The cat Command
The following code demonstrates the first option for running an SQL script from a file in SQLite.
cat create_table.sql | sqlite3 Test.db
This assumes my script is called create_table.sql and I want to run it against the Test.db database.
I was able to run this script directly from my Terminal window, without connecting to SQLite using the SQLite3
command.
The .read Command
If you’re already connected to SQLite, you can use the .read
command.
.read insert_data.sql
This example reads the script insert_data.sql from the current folder/directory. Specify the full path if in a different directory.
Use the .read Command Without Opening SQLite
Here’s another way of using the .read
command.
sqlite3 Test.db ".read insert_data.sql"
Doing this will insert the data into the specified database from the command line.
The difference between this example and the previous, is that the previous one was done from within SQLite after you’d already connected. However, with this example, you run it from outside of SQLite.
If you’re on Windows, you might need to do this:
sqlite3.exe Test.db ".read insert_data.sql"
Redirect the Input to the Database when Connecting to SQLite
The following method redirects the input to the database file when using sqlite3
to connect to SQLite and open the database.
sqlite3 Test.db < insert_data.sql
The -init Option
Here’s yet another way you can run SQL scripts from a file with SQLite.
sqlite3 Test.db -init insert_data.sql