python list in sql query as parameter

Saturday, November 22nd, 2008
Advertisement

Subscribe.
Enter your email:

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.

If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

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

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

One Response to “python list in sql query as parameter”

  1. Hanep says:

    wish i can learn all these… huhuhu

    Haneps last blog post..Google dah update pagerank, betul ke?

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>