2015-10-05 143 views
0

我知道有关于此错误的堆栈溢出有许多问题,但我尝试了很多解决方案,显然它们都失败了。Python 3 SQLite3 - 绑定数量不正确

这里有一个列表:

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

SQLite parameter substitution problem

sqlite3.ProgrammingError: Incorrect number of bindings supplied

Reading from database with SQLite and Python: Incorrect number of binding supplied

SQLite Python Insert - Incorrect Number of Bindings Supplied

我试图在SQLite3数据库中存储用户名和密码(由PassLib - https://pythonhosted.org/passlib/创建)。这些分别存储在变量“targetusername”和“password”中。我的问题是,当我真正尝试这两个变量插入一个名为“密码”数据库的表中,给出了这样的错误:

Incorrect number of bindings supplied. The current statement uses 1, and there are 11 supplied. 

这里是什么targetusername和密码将存储的例子:

targetusername = "user4884072" 
password = "$5$rounds=535000$ySH31paWMjEDCUUY$jdrBVGsoYnSMkdVBtjCaxQy2f0g3MX1Wts4vSYz7m.4" 

此行给出了错误:

c.executemany("INSERT INTO {tn} ({idf}, {cn}) VALUES(targetusername, %s" % str(password).\ 
format(tn="Passwords")) 

已多次更改,试图解决这个问题(这显然是受了Python的商店变量引起的),除H ERE是它原是:

c.execute("INSERT OR IGNORE INTO {tn} ({idf}, {cn}) VALUES (targetusername, password)".\ 
format(tn="Passwords", idf="Username", cn="Password")) 

回答

2

使用c.execute(),不c.executemany(),插入数据的单行。这是您遇到的错误的直接原因。

除此之外,不要使用字符串替换,使用参数化查询。这是一个完整的工作示例:

import sqlite3 

connection = sqlite3.connect(':memory:') # in memory database 
c = connection.cursor() 

c.execute('create table Passwords (Username text, Password text)') 

targetusername = "user4884072" 
password = "$5$rounds=535000$ySH31paWMjEDCUUY$jdrBVGsoYnSMkdVBtjCaxQy2f0g3MX1Wts4vSYz7m.4" 
c.execute('insert into Passwords (Username, Password) values (?, ?)', (targetusername, password)) 
print c.execute('select * from Passwords').fetchall() 

输出:

 
[(u'user4884072', u'$5$rounds=535000$ySH31paWMjEDCUUY$jdrBVGsoYnSMkdVBtjCaxQy2f0g3MX1Wts4vSYz7m.4')] 

在你已经张贴有在表或列名替换值没有意义的代码,所以只是把它们放在查询字符串如图所示。

这使用参数化查询,其中API将用户名和密码的值插入?表示的地方的查询中。这比使用字符串替换更安全,因为DB API知道如何正确安全地转义传递给它的值,并且这可以避免对代码执行SQL注入攻击。

它使用​​而不是executemany(),因为只有一行数据被插入。

+0

尝试解决方案后出现同样的错误。 – user4884072

+0

@ user4884072:真的吗?我用一个完整的工作示例更新了我的答案。尝试运行它。我还建议你用可以工作的代码更新你的问题(你的第一个例子导致'TypeError')并且证明问题。 – mhawke

相关问题