tags:

views:

110

answers:

1

I have the follow sql statement in a program I am building, where id_list is sometimes a very large list.

for id in id_list:
    self.cursor.execute("""update songs set rating='L' where trackid=?""", (id,))
self.db.commit()

Is there a more efficient way of doing this that doesn't involve so many update queries?

+2  A: 

SQL:

update songs set rating='L' where trackid IN (id_list)

Code:

self.cursor.execute("update songs set rating='L' where trackid IN (%s)"%','.join(['?']*len(id_list)), id_list)
self.db.commit()

There is also more elegant, but suboptimal solution:

self.cursor.executemany("update songs set rating='L' where trackid=?", id_list)
self.db.commit()
vartec
The second options appears to be the same as the original poster has.
Karl
Not at all. Instead of for loop, there is excecute**many**
vartec
Thanks, I used your 1st solution and everything works as it should.
wodemoneke