从python列表中删除带有信息的MYSQL中的多行 [英] Delete multiple rows in MYSQL with info from python list
本文介绍了从python列表中删除带有信息的MYSQL中的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果列表LL:
LL = ['foo', bar', 'noo', 'boo',]
在MySQL表中,在具有其他ID的列ID中进行测试.
is in a MySQL table, test in column ID with other ID's.
我可以使用以下命令删除LL中ID为的所有行:
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"; """)
我该如何编程?
推荐答案
您可以通过一个查询来做到这一点:
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)
由于cursor.execute在进行替换时会转义字符串,因此该示例可以安全地防止SQL注入.
Since cursor.execute escapes strings when doing substitutions, this example is safe against SQL injections.
这篇关于从python列表中删除带有信息的MYSQL中的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文