views:

58

answers:

2

I have a list of ints that I want to join into a string

ids = [1,2,3,4,5]

that looks like 'Id = 1 or Id = 2 or Id = 3 or Id = 4 or ID = 5'

I have an answer now but I thought it may be good to get the panel's opinion

Edit: More information to the nay sayers... This not generating SQL directly, this is dynamic expression that is being sent to a Ado.net data services layer that uses Entity Framework underneath. The IN clause which is what is preferred is currently not supported by the dynamic expression handler/EF4 adapter in the service yet and I have to resort to multiple equals statements for the time being.

+4  A: 
" or ".join("id = %d" % id for id in ids)
kindall
on my machine, replacing the old style formatting with new style drops it from 14usec to 9.3usec. Of course it's still not as good as 7.34 usecs that you get by avoiding string formatting ;)
aaronasterling
@arron - please could you elaborate
Preet Sangha
He's talking about `"id = %d" % id` vs. `"id = {}".format(id)` (old vs. new).
ma3
+1  A: 
mystring = 'id =' + 'or id ='.join(str(i) for i in ids)

If you want to generate dynamic sql as those in the comments have pointed out (don't know how I missed it), you should be doing this as

mystring = ' or '.join(['id = ?']*len(ids))  

where ? is meant to be replaced with the appropriate escape sequence for your database library. For sqlite3, that's ?. for MySQLdb, it uses the printf codes, IIRC. You can then pass the list of id's to the cursor as the second argument (usually) after the sql string and it will put them in there in a secure way. This is always the right thing.

aaronasterling
Thank you, the its not dynamic in the standard sense, rather is a predicate expression that is being sent to a ADO.NET Data Services (EF4 ORM underneath) service.
Preet Sangha