2017-02-21 116 views
0

我正在使用python 3.5,並試圖將列表元素插入到表中。SQLite3 - 在表中插入列表項

名單已經確定:

list1 = [1,2,3...] 
list2 = [1,2,3...] 
list3 = [1,2,3...] 
list4 = [1,2,3...] 
list5 = [1,2,3...] 

連接到數據庫:

conn = sqlite3.connect('database.db') 
c = conn.cursor() 

創建一個表,表1,有5列:

def create_table(): 
    c.execute("CREATE TABLE IF NOT EXISTS Table1(Column1 TEXT, Column2 TEXT, Column3 TEXT, 
Column4 TEXT, Column5 TEXT)") 

並添加名單元素表:

def data_entry(): 
    Column1 = list1 
    Column2 = list2 
    Column3 = list3 
    Column4 = list4 
    Column5 = list5 
    c.execute("INSERT INTO Master (Column1, Column2, Column3, Column4, Column5) 
VALUES (?, ?, ?, ?, ?)", (Column1, Column2, Column3, Column4, Column5)) 
    conn.commit() 

c.close() 
conn.close() 

當我運行它,我得到:

ProgrammingError:提供的綁定數有誤。當前的語句使用5,並提供了150。

將循環更適合用來插入每個項目列表作爲指定列中的新行嗎?如果是這樣,我該如何爲sqlite3創建一個循環?

這是我第一次使用sqlite3,所以任何建議都非常感謝。謝謝!

+0

你想輸入行或列? –

+0

我試圖將每個列表元素作爲指定列中的新行輸入 – John

回答

1

你必須遍歷列表(假設他們有相同的長度):

for i in range(len(list1)): 
    c.execute("INSERT INTO Master (Column1, Column2, Column3, Column4,Column5)" 
       " VALUES (?, ?, ?, ?, ?)", 
       (list1[i], list2[i], list3[i], list4[i], list5[i])) 
+0

完美工作,謝謝! – John

1

你可以使用一些快捷方式,它的效率更高:

import sqlite3 

list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
list3 = [7, 8, 9] 

con = sqlite3.connect(":memory:") 
con.execute("CREATE TABLE master(col1, col2, col3)") 
con.executemany("INSERT INTO master(col1, col2, col3) VALUES (?, ?, ?)", (list1, list2, list3)) 
for row in con.execute("SELECT col1, col2, col3 FROM master"): 
    print(row)