Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a CSV file into a sqlite3 database table using Python

I have a CSV file and I want to bulk-import this file into my sqlite3 database using Python. the command is ".import .....". but it seems that it cannot work like this. Can anyone give me an example of how to do it in sqlite3? I am using windows just in case. Thanks

like image 962
Hossein Avatar asked May 22 '10 11:05

Hossein


People also ask

How do I import a CSV file into SQLite database?

First, from the menu choose tool menu item. Second, choose the database and table that you want to import data then click the Next button. Third, choose CSV as the data source type, choose the CSV file in the Input file field, and choose the ,(comma) option as the Field separator as shown in the picture below.

How do I convert a CSV file to a table in Python?

You can read a CSV file into a DataFrame using the read_csv() function (this function should be familiar to you, but you can run help(pd. read_csv) in the console to refresh your memory!). Then, you can call the . to_sql() method on the DataFrame to load it into a SQL table in a database.


2 Answers

import csv, sqlite3  con = sqlite3.connect(":memory:") # change to 'sqlite:///your_filename.db' cur = con.cursor() cur.execute("CREATE TABLE t (col1, col2);") # use your column names here  with open('data.csv','r') as fin: # `with` statement available in 2.5+     # csv.DictReader uses first line in file for column headings by default     dr = csv.DictReader(fin) # comma is default delimiter     to_db = [(i['col1'], i['col2']) for i in dr]  cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db) con.commit() con.close() 
like image 78
mechanical_meat Avatar answered Sep 20 '22 21:09

mechanical_meat


Creating an sqlite connection to a file on disk is left as an exercise for the reader ... but there is now a two-liner made possible by the pandas library

df = pandas.read_csv(csvfile) df.to_sql(table_name, conn, if_exists='append', index=False) 
like image 33
Tennessee Leeuwenburg Avatar answered Sep 22 '22 21:09

Tennessee Leeuwenburg