Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select from sqlite table where rowid in list using python sqlite3 — DB-API 2.0

Tags:

python

sqlite

The following works:

>>> cursor.execute("select * from sqlitetable where rowid in (2,3);")

The following doesn't:

>>> cursor.execute("select * from sqlitetable where rowid in (?) ", [[2,3]] )
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

Is there a way to pass in a python list without having to format it into a string first ?

like image 503
Naveen Avatar asked Apr 23 '11 18:04

Naveen


2 Answers

Unfortunately not. Each value must be given its own parameter mark (?). Since the argument list can (presumably) have arbitrary length, you must use string formating to build the correct number of parameter marks. Happily, that isn't so hard:

args=[2,3]
sql="select * from sqlitetable where rowid in ({seq})".format(
    seq=','.join(['?']*len(args)))

cursor.execute(sql, args)
like image 80
unutbu Avatar answered Oct 14 '22 01:10

unutbu


In Python 3.6 you can also build queries with the f strings:

args=[2, 3]
query = f"SELECT * FROM sqlitetable WHERE rowid in ({','.join(['?']*len(args))})"
cursor.execute(query, args)
like image 41
Bruno Vermeulen Avatar answered Oct 14 '22 01:10

Bruno Vermeulen