2013-10-10 116 views
0

什麼是製作腳本的最佳方式是使用CSV(帶有n列)並將它們添加到sqlite數據庫中?在sqlite中插入多個變量 - python

這是我到現在爲止 - (?調用者應該知道,是不是他)

def export_to_db(): 
    conn = sqlite3.connect(config.DB_NAME) 
    cur = conn.cursor() 
    table_name = config.TABLE_NAME 
    with open(config.IMPORT_FILENAME, 'rb') as csvfile: 
     tablerows = csv.reader(csvfile, delimiter=',') 
     header = True # make this configurable 
     for row in tablerows: 
      if header: 
       header = False 
      else: 
       cur.execute("INSERT INTO <tablename> VALUES(?, ?, ?, ?)", tuple(row)) 
       # I want the number of columns to be same as teh number of columns in CSV.    
    conn.commit() 
    cur.execute("SELECT COUNT(*) from people") 
    print str(cur.fetchone()[0]) + " rows added!" 
    conn.close() 

回答

0

明顯的解決辦法是使配置的列數,然後建立自己的INSERT語句基於這個信息。如果您不知道如何操作,請閱讀FineManual關於字符串格式的部分。