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))
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))
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
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)) + ')'
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)) + ')'
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.sql = 'select * from studens where ' +
' or '.join(('id = ' + str(n) for n in id))
Note: The above codes were tested using Sqlite3 and Python 2.5.