Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get variable length placeholders in a Python call to SQLite3

Tags:

python

sqlite

Is there a way to use variable length placeholders in an SQL query?

Right now with a 3-tuple, I write something like this:

c.execute('SELECT * FROM table WHERE word IN (?, ?, ?)', tup)

But what if the tup can be of differing lengths, perhaps a 4-tuple or 2-tuple? Is there a syntax for using placeholders in this situation? If not, what is the preferred way to write the code?

like image 759
Raymond Hettinger Avatar asked Nov 03 '11 06:11

Raymond Hettinger


1 Answers

You'd have to do something like this (to use your example):

tup = ... # some sequence/tuple of unknown length
sql = 'SELECT * FROM table WHERE word IN (%s)' % ', '.join('?' for a in tup)
c.execute(sql, tup)

This way you're dynamically creating the placeholder list and formatting the SQL string before the sqlite3 module parses it out.

like image 151
rossipedia Avatar answered Nov 09 '22 04:11

rossipedia