I'm trying to create a web application where users can input their csv data that I will then return analysis to the user. CSV data files can come in various sizes and number of fields, so I have to be able to dynamically create tables in my sqlite database.
So far, I've created a very rough and hackish way of creating tables, but now I'm simply stuck at being able to insert queries into the table. I am aware of DictReader, which I have been trying to incorporate it after reading this answer. However, the INSERT query in the Python script
with open('data.csv','rb') 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)
is based on a fixed number of fields. I can't find a way to dynamically make (col1, col2) VALUES (?, ?) work.
Here is what I've done so far to dynamically CREATE tables.
import sqlite3, csv
conn = sqlite3.connect("test.db")
cur = conn.cursor()
csv_file = open("test.csv", "rb")
csv_reader = csv.reader(csv_file)
header = csv_reader.next()
header_str = ', '.join(str(e) for e in header)
sql = "CREATE TABLE t (%s) " % header_str
cur.execute(create_SQL_str)
I used the header row to determine to make a string from the list that is header. I then made a CREATE SQL query and used string format (I'm aware that parameterized values with ? is better, but this isn't my primary concern at the moment.)
However, I don't think I can do the same type of hackish solution for INSERT query.
Is there an easy solution to this that I missed? I've been looking everywhere for a better solution, but couldn't find one.