Question

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?

Was it helpful?

Solution

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top