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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With