csv to sqlite python

Solutions on MaxInterview for csv to sqlite python by the best coders in the world

showing results for - "csv to sqlite python"
Salomé
11 Apr 2016
1import csv, sqlite3
2
3con = sqlite3.connect(":memory:") # change to 'sqlite:///your_filename.db'
4cur = con.cursor()
5cur.execute("CREATE TABLE t (col1, col2);") # use your column names here
6
7with open('data.csv','r') as fin: # `with` statement available in 2.5+
8    # csv.DictReader uses first line in file for column headings by default
9    dr = csv.DictReader(fin) # comma is default delimiter
10    to_db = [(i['col1'], i['col2']) for i in dr]
11
12cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
13con.commit()
14con.close()
15