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.
Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010








wish i can learn all these… huhuhu
Haneps last blog post..Google dah update pagerank, betul ke?