2017-06-02 30 views
0

我有以下代碼動態插入到SQLite數據庫錯誤

cur.executemany("INSERT INTO "+tablename+" (name,"+item+") VALUES(?,?)",(data,))

動態地從data 插入值,現在我有兩個問題: 如果我使用的語法VALUES(?,?)",(data))沒有, after data 我會得到這個錯誤

Error Incorrect number of bindings supplied. The current statement uses 2, and there are 4 supplied.: 

這是隻使用語法解決VALUES(?,?)",(data,)),

它解決了這個問題,數據被插入表中。 但它創建我無法查詢數據庫,並使用類似

cursor = cur.execute("select * from "+tablename+" where name="+name+"")

我會得到這個錯誤的另一個問題:

Error no such column: deek: 

我不知道如何查詢DB使用上述語法。

我得到了上面的語法從 sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

完整的代碼以供參考:

import sqlite3 
import sys 
tablename='asfoor' 
table_data=['Name','a','b','c'] 

try: 
    con = sqlite3.connect('dbtrials.db') 
    cur = con.cursor() 
    cur.execute("DROP TABLE IF EXISTS "+tablename+"") 
    cur.execute("CREATE TABLE "+tablename+" (ID INTEGER PRIMARY KEY AUTOINCREMENT ,Name TEXT, "+table_data[1]+" TEXT, "+table_data[2]+" TEXT, "+table_data[3]+" TEXT)") 



    name='deek' 
    item='a' 
    data=[name,item] 
    cur.executemany("INSERT INTO "+tablename+" (name,"+item+") VALUES(?,?)",(data,)) 
    cursor = cur.execute("select * from "+tablename+" where name="+name+"") 
    for row in cursor : 
       print(row) 


except sqlite3.Error as e: 

    print ("Error %s:" % e.args[0]) 
    sys.exit(1) 

finally: 

    if con: 
     con.close() 
+0

是一樣的,如果我使用VALUES(?,?)」,(名稱,項目))我仍然得到相同的錯誤'當前語句使用2,並且有4個提供' –

回答

1

的原因錯誤是因爲你忘了把字符串引號包圍。它應該是:

cursor = cur.execute("select * from "+tablename+" where name='"+name+"'") 

但它會更好地使用參數化查詢:

cursor = cur.execute("select * from "+tablename+" where name= %s", (name,)) 
1

executemany預計迭代器作爲第二個參數序列或映射的。 您的輸入應該是這樣的:data = [[name, item]]

所以查詢你所期望:

  1. deeka(2個參數)

沒有內部列表所花費的字符串序列chars所以你的查詢是:

  1. deek(4參數)

  2. a(1 ARG)