Delete multiple rows in MYSQL with info from python list

拥有回忆 提交于 2019-12-05 05:14:29

问题


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?


回答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.




回答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.




回答3:


for item in LL:
    csr.execute("DELETE FROM test.test WHERE ID = '%s'", item)

like that?



来源:https://stackoverflow.com/questions/5955841/delete-multiple-rows-in-mysql-with-info-from-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!