2015-11-06 202 views
0
select=input("select: ") 
    for row in data.execute('select ? from stocks where date like "2015-11-05" ',(select)): 

     print(row) 

這就是我現在要做的所有事情,但是我得到這個錯誤, t找到解決方案python sql,「select?from table where?like?」,(selected,where,like))

sqlite3.ProgrammingError: Incorrect number of bindings supplied. 
    The current statement uses 1, and there are 5 supplied. 

有沒有辦法做到這一點?我假設答案與標題類似。

回答

0

(select)不是一個元組,它是一個字符串,在你的情況下是一個由5個字符組成的字符串。由於字符串也是可迭代的,因此sqlite會將字符串拆分爲字符並嘗試使用字符串中的所有5個字符對查詢進行參數化。相反,你的意思是有內部的單個元素的元組:

data.execute('select ? from stocks where date like "2015-11-05" ', (select,)) 

但是,問題是 - 這是行不通的,你cannot parameterize the table or column names,你不得不使用字符串格式化:

data.execute('select {} from stocks where date like "2015-11-05"'.format(select)) 

請注意,由於我們在此處使用字符串格式,因此我們正在使代碼容易受到SQL注入的影響 - 您應該肯定驗證select變量值並保護自己免受SQL注入(不確定在您的情況下誰將成爲程序的用戶雖然)。

+0

@ user5464854很高興幫助,請參閱http://stackoverflow.com/help/someone-answers。 – alecxe

相關問題