开发者

Python SQL Select statement from a list variable?

I am trying to query my sqlite3 db and use values from a list. Here's my code:

for i in range(len(infolist)):
    result = cursor.execute('SELECT COUNT(DISTINCT col1) 
                               FROM tablename 
                              WHERE col2 = ?', (infolist[i]))

I receive this error:

ProgrammingError: 'Incorre开发者_开发问答ct number of bindings supplied. The current statement uses 1, and there are 22 supplied.'

The string has 22 characters which explains why there are 22 bindings. Clearly I'm not passing the string correctly into the SQL statement.


The second argument to cursor.execute is a sequence and you have passed it a string (which is a sequence of characters). If you are trying to do a 1 element tuple, you need a comma. i.e. ('item',) instead of ('item')

Also you should iterate over the items and not use range and i:

for info in infolist:
    result = cursor.execute('SELECT COUNT(DISTINCT col1) 
                               FROM tablename 
                              WHERE col2 = ?', (info,))


You need to add a comma to the end of (infolist[i]) right now it's a 22 character string not a tuple. (infolist[i],) should fix that


You need to add a comma to indicate the tuple has 1 element:

>>> ('abc')
'abc'
>>> ('abc',)
('abc',)

Try passing (infolist[i],) to cursor.execute.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜