Sunday, November 23, 2008

python list in sql query as parameter

Suppose that we have a list [10, 20, 4, 6, 9], and we want to write a sql query to get the data for all elements of the list, like
select * from students where id in (10, 20, 4, 6, 9)
How to do that in Python? Actualy, it is very easy. Below are the list of techniques to do it:

Technique 1

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where id in %s' % str(tuple(id))

Technique 2

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where id in (%s)' % ','.join(map(str, id))

Technique 3

id = [10, 20, 4, 6, 9]
xx = ', '.join(id)
sql = 'select * from students where id in (%s)' % xx

Technique 4

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where id in (' +
         ','.join(map(str, id)) + ')'

Technique 5

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where id in (' +
         ','.join((str(n) for n in id)) + ')'

Technique 6

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where ' +
         ' or '.join(('id = ' + str(n) for n in id))
I prefer the first technique. What about you? Do you have some other techniques to share? If you do, please leave a comment. Thank you.

Note: The above codes were tested using Sqlite3 and Python 2.5.