Python SQL Select statement from list variable?

I am trying to query a sqlite3 database and use the values ​​from a list. Here is my code:

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

I get this error:

ProgrammingError: 'Invalid number of bindings. The current statement uses 1 and sends 22 to it.

The string contains 22 characters, which explains why there are 22 bindings. Clearly, I am not passing the string correctly to the SQL statement.

+5
source share
3 answers

cursor.execute - , ( ). 1 , . .. ('item',) ('item')

i:

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

(infolist[i]) , 22 , . (infolist[i],) ,

+1

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

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

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

0
source

All Articles