115

I need to dump a .sql or .csv file into SQLite (I'm using SQLite3 API). I've only found documentation for importing/loading tables, not entire databases. Right now, when I type:

sqlite3prompt> .import FILENAME TABLE 

I get a syntax error, since it's expecting a table and not an entire DB.

StayOnTarget
  • 7,829
  • 8
  • 42
  • 59
happythenewsad
  • 1,685
  • 3
  • 14
  • 16

11 Answers11

164

To import from an SQL file use the following:

sqlite> .read <filename>

To import from a CSV file you will need to specify the file type and destination table:

sqlite> .mode csv <table>
sqlite> .import <filename> <table>
Jay Igor
  • 1,746
  • 1
  • 9
  • 4
  • 2
    This is the right answer, but sometimes it chokes on funky/broken CSV files. – Eli Jun 25 '09 at 20:26
  • It is giving error "cannot open db.sql",when I am using .read commond. – Dory Nov 24 '14 at 05:41
  • 2
    how does it get the column names , if they are not present in the csv file ? – sumanth232 Mar 28 '15 at 09:26
  • @krishna222, per [the documentation](http://www.sqlite.org/cli.html#csv_import), if the table does not exist, the first line of the CSV will be used as column names; if the table does exist, all rows are treated as data. – alttag Dec 01 '16 at 22:52
26

Try doing it from the command like:

cat dump.sql | sqlite3 database.db

This will obviously only work with SQL statements in dump.sql. I'm not sure how to import a CSV.

Kyle Cronin
  • 72,761
  • 40
  • 144
  • 160
  • I think this would work just the same, but the user would have to make sure that the sqlite3 settings were set up for `.mode csv` – FilBot3 Oct 29 '13 at 15:52
  • Just want to make a comment here, this is actually 100% dead on, `sqlite3 database.db < dump.sql` is SOOOO SLOW!!! So use `cat dump.sql | sqlite3 database.db` instead! :D – Javier Buzzi Jun 20 '16 at 16:50
  • @JavierBuzzi: Sorry but that makes no sense. Those two methods are equivalent. You must have had something else going on when you tried one method or the other. Under stable testing conditions I guarantee there will be no speed difference. – IcarusNM Feb 17 '17 at 18:40
22

To go from SCRATCH with SQLite DB to importing the CSV into a table:

  • Get SQLite from the website.
  • At a command prompt run sqlite3 <your_db_file_name> *It will be created as an empty file.
  • Make a new table in your new database. The table must match your CSV fields for import.
  • You do this by the SQL command: CREATE TABLE <table_Name> (<field_name1> <Type>, <field_name2> <type>);

Once you have the table created and the columns match your data from the file then you can do the above...

.mode csv <table_name>
.import <filename> <table_name>
Alexander Farber
  • 18,345
  • 68
  • 208
  • 375
Jake Wyman
  • 281
  • 2
  • 2
11

The sqlite3 .import command won't work for ordinary csv data because it treats any comma as a delimiter even in a quoted string.

This includes trying to re-import a csv file that was created by the shell:

Create table T (F1 integer, F2 varchar);
Insert into T values (1, 'Hey!');
Insert into T values (2, 'Hey, You!');

.mode csv
.output test.csv
select * from T;

Contents of test.csv:
1,Hey!
2,"Hey, You!"

delete from T;

.import test.csv T
Error: test.csv line 2: expected 2 columns of data but found 3

It seems we must transform the csv into a list of Insert statements, or perhaps a different delimiter will work.

Over at SuperUser I saw a suggestion to use LogParser to deal with csv files, I'm going to look into that.

blairxy
  • 363
  • 3
  • 8
  • blairxy: The error you are getting is due to comma in "Hey, You!". While loading 2nd line Sqlite sees 3 columns and on removing 2nd comma you can load it without error. – Shiva Oct 31 '13 at 00:07
10

If you are happy to use a (python) script then there is a python script that automates this at: https://github.com/rgrp/csv2sqlite

This will auto-create the table for you as well as do some basic type-guessing and data casting for you (so e.g. it will work out something is a number and set the column type to "real").

Rufus Pollock
  • 2,155
  • 18
  • 19
  • Almost works--the header row imports OK. However then I get `sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings` # csv2sqlite.py {csv-file-path} {sqlite-db-path} [{table-name}] – Marcos Apr 23 '13 at 13:45
  • Hmmm, i've never seen that error using this. Were you using non-unicode or non-utf8 data? If so you may need to tweak the script to open the CSV file using the specific encoding it is using. – Rufus Pollock May 04 '13 at 13:33
  • Around the same time, I wrote a ruby script that does the same thing!! It should even work on multiple CSV files at once, guessing the table name from the file name. https://github.com/dergachev/csv2sqlite – Dergachev Sep 20 '13 at 13:38
  • We would need to read from sys.stdin since we need to convert a 60GB csv.gz file. Or, would there be a chance to get gzip read support into csv2sqlite? Thanks! – markusN Nov 21 '14 at 15:07
  • @markusN open an issue on the github tracker. Generally, i would worry about a 100GB+ CSV file in sqlite (have you though about a "proper" RDB e.g. postgres or even bigquery, redshift etc – Rufus Pollock Feb 22 '15 at 21:40
7

Remember that the default delimiter for SQLite is the pipe "|"

sqlite> .separator ";"

sqlite> .import path/filename.txt tablename 

http://sqlite.awardspace.info/syntax/sqlitepg01.htm#sqlite010

Alexander Farber
  • 18,345
  • 68
  • 208
  • 375
DnD
  • 173
  • 2
  • 7
2

Check out termsql. https://gitorious.org/termsql https://gitorious.org/termsql/pages/Home

It converts text to SQL on the command line. (CSV is just text)

Example:

cat textfile | termsql -o sqlite.db

By default the delimiter is whitespace, so to make it work with CSV that is using commata, you'd do it like this:

cat textfile | termsql -d ',' -o sqlite.db

alternatively you can do this:

termsql -i textfile -d ',' -o sqlite.db

By default it will generate column names "COL0", "COL1", if you want it to use the first row for the columns names you do this:

termsql -i textfile -d ',' -1 -o sqlite.db

If you want to set custom column names you do this:

termsql -i textfile -d ',' -c 'id,name,age,color' -o sqlite.db
Alexander Farber
  • 18,345
  • 68
  • 208
  • 375
user3573558
  • 182
  • 1
1

SQLite is extremely flexible as it also allows the SQLite specific dot commands in the SQL syntax, (although they are interpreted by CLI.) This means that you can do things like this.

Create a sms table like this:

# sqlite3 mycool.db '.schema sms'
CREATE TABLE sms (_id integer primary key autoincrement, Address VARCHAR, Display VARCHAR, Class VARCHAR, ServiceCtr VARCHAR, Message VARCHAR, Timestamp TIMESTAMP NOT NULL DEFAULT current_timestamp);

Then two files:

# echo "1,ADREZZ,DizzPlay,CLAZZ,SMSC,DaTestMessage,2015-01-24 21:00:00">test.csv

# cat test.sql
.mode csv
.header on
.import test.csv sms

To test the import of the CSV file using the SQL file, run:

# sqlite3 -csv -header mycool.db '.read test.sql'

In conclusion, this means that you can use the .import statement in SQLite SQL, just as you can do in any other RDB, like MySQL with LOAD DATA INFILE etc. However, this is not recommended.

not2qubit
  • 10,014
  • 4
  • 72
  • 101
1

if you are using it in windows, be sure to add the path to the db in "" and also to use double slash \ in the path to make sure windows understands it.

MahD
  • 3
  • 2
0

This is how you can insert into an identity column:

CREATE TABLE my_table (id INTEGER PRIMARY KEY AUTOINCREMENT, name COLLATE NOCASE);
CREATE TABLE temp_table (name COLLATE NOCASE);

.import predefined/myfile.txt temp_table 
insert into my_table (name) select name from temp_table;

myfile.txt is a file in C:\code\db\predefined\

data.db is in C:\code\db\

myfile.txt contains strings separated by newline character.

If you want to add more columns, it's easier to separate them using the pipe character, which is the default.

live-love
  • 34,372
  • 16
  • 163
  • 152
-1

Import your csv or sql to sqlite with phpLiteAdmin, it is excellent.

Karra Max
  • 124
  • 1
  • 9