5

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: 'Incorrect 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.

1
  • 1
    Using the IN clause, if the array can be turned into a comma separated list, would work better & alleviate the need for the loop. Commented May 20, 2011 at 1:54

3 Answers 3

1

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,))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the info, what are your thoughts on iterating multiple lists ie. for i in range(len(infolist)): cursor.execute('UPDATE tabledata SET col1=?,col2=? WHERE col3=?', (infolist[i], infolist2[i], infolist3[i]))
That's another question but cursor.executemany('UPDATE tabledata SET col1=?,col2=? WHERE col3=?', zip(inforlist, infolist2, infolist3)) is what you want.
1

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

Comments

0

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.