Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple rows in MYSQL with info from python list

If list LL:

LL = ['foo', bar', 'noo', 'boo',]

is in a MySQL table, test in column ID with other ID's.

I could use the following to delete all rows with ID's in LL:

 csr.execute("""DELETE FROM test.test WHERE ID = "Foo"; """)
  csr.execute("""DELETE FROM test.test WHERE ID = "bar"; """)  
  csr.execute("""DELETE FROM test.test WHERE ID = "noo"; """)
  csr.execute("""DELETE FROM test.test WHERE ID = "boo"; """)  

How could I do it programatically?

like image 912
Merlin Avatar asked Jan 19 '23 19:01

Merlin


2 Answers

You can do it with a single query:

id_list = ['abc', 'def', 'ghi']
query_string = "delete from test where id in (%s)" % ','.join(['?'] * len(id_list))
cursor.execute(query_string, id_list)

Since cursor.execute escapes strings when doing substitutions, this example is safe against SQL injections.

like image 144
sapht Avatar answered Jan 30 '23 23:01

sapht


String formatters - http://docs.python.org/library/string.html#format-string-syntax

["""DELETE FROM test.test WHERE ID = "%s"; """ % x for x in LL]

and then run each of the SQL statements in the list.

like image 21
dfb Avatar answered Jan 31 '23 00:01

dfb