Skip to content Skip to sidebar Skip to footer

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(

Solution 1:

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.

Solution 2:

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.

Solution 3:

Solution 4:

For MySQL you need to use %s instead of ? as the parameter marker. And don't forget to commit.

product_list = [645, 64, 9785, 587]
query = "DELETE FROM products WHERE id IN (%s)" % ",".join(["%s"] * len(product_list))
cursor.execute(query, product_list)
connection.commit()

Solution 5:

Just convert the list into a string format with comma-separated and use a normal where clause with in condition.

id_list = ['abc', 'def', 'ghi']
id_list_string = "', '".join(id_list)
delete_query = "delete from test where id in ('" +id_list_string+"')"
dbconnection.execute(delete_query)

Post a Comment for "Delete Multiple Rows In Mysql With Info From Python List"