title: How to dynamically import CSV files to sqlite
body: <p>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. </p>
  
  <p>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 <a href="https://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python">answer</a>. However, the INSERT query in the Python script</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>is based on a fixed number of fields. I can't find a way to dynamically make (col1, col2) VALUES (?, ?) work.</p>
  
  <p>Here is what I've done so far to dynamically CREATE tables.</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>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.)</p>
  
  <p>However, I don't think I can do the same type of hackish solution for INSERT query.</p>
  
  <p>Is there an easy solution to this that I missed? I've been looking everywhere for a better solution, but couldn't find one.</p>