Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Sqlite3 Script from Command Line

I am writing a shell script to scp a project and part of it involves transferring some important tables in my database.

I have the following stored in the file SQLTableTransfer:

.o MyTable1.sql;
.dump MyTable1;

.o MyTable2.sql;
.dump MyTable2;

.o MyTable3.sql;
.dump MyTable3;

And took a chance on

$ sqlite3 SQLTableTransfer

But this just opened the Sqlite3 shell. What is the correct way to run a script like this from the command line?

like image 835
rwolst Avatar asked Feb 13 '14 15:02

rwolst


People also ask

How do I access SQLite from command line?

Start the sqlite3 program by typing "sqlite3" at the command prompt, optionally followed by the name the file that holds the SQLite database (or ZIP archive). If the named file does not exist, a new database file with the given name will be created automatically.

How do I open SQLite file in SQL?

Import the SQL fileOpen DB Browser for SQLite. Choose “File” > “Import” > “Database” from SQL file from the menu bar at the top of your screen.

What is sqlite3 command?

sqlite3 is a terminal-based front-end to the SQLite library that can evaluate queries interactively and display the results in multiple formats. sqlite3 can also be used within shell scripts and other applications to provide batch processing features.


4 Answers

The parameter you give to the sqlite3 program is the database file name.

To execute commands from a file, you must redirect the input to that file:

$ sqlite3 mydatabase.db < SQLTableTransfer

or tell it to read from that file:

$ sqlite3 mydatabase.db ".read SQLTableTransfer"
like image 166
CL. Avatar answered Nov 05 '22 11:11

CL.


You can get a list of the spatial tables as follows:

echo "SELECT f_table_name FROM geometry_columns;" | spatialite -noheader -silent your_db.sqlite

like image 25
Micha Avatar answered Nov 05 '22 09:11

Micha


For the lazy who want to just dump this into their .bashrc:

### Execute an sqlite3 file on a given db
sql3-exec () {
  # TODO: write a  --help flag that doubles as error handling
  # TODO: Ensure that $1 is a db; Else display --help
  # TODO: Ensure that $2 is a .sql file; Else display --help
  # TODO: Probably store a backup (or at least a flag)...
  sqlite3 $1 ".read $2"
  true
}
like image 37
T.Woody Avatar answered Nov 05 '22 11:11

T.Woody


For Windows CLI, assuming your database is loaded:

sqlite> .read C:\\somesubdir\\some.sql
like image 41
Andrew Cowenhoven Avatar answered Nov 05 '22 11:11

Andrew Cowenhoven