2011-05-10 68 views
2

在MYSQL删除多行与信息如果列表LL:从Python列表

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

是在一个MySQL表,测试中列ID与其它ID的。

我可以使用下面的ID为在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"; """) 

我怎么能做到这一点编程?

回答

5

您可以使用单个查询做到这一点:在做替换时

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注入安全。

+0

不,请查看答案中的查询字符串如何显示“where id in ...”not“where id = ...” – 2011-05-10 20:33:13

+0

@ user428862“in('abc','hjk',...)”适用于MySQL的。它优先于“where id ='abc'或id ='hjk'”。但是,我的例子包含语法错误和数字ID。尝试更新的版本。 – sapht 2011-05-10 20:34:10

+0

id_list = ['acb','def',] SQL包含0个参数标记,但提供了2个参数' – Merlin 2011-05-10 20:39:29

1

字符串格式化 - http://docs.python.org/library/string.html#format-string-syntax

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

,然后运行列表中的每个SQL语句的。

+0

“LL”仅包含可信项目至关重要。如果它包含来自不受信任来源的数据并且没有正确转义,则可以使用SQL注入。 – 2017-07-23 08:21:09

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

那样?

+0

每个?不需要.. – Merlin 2011-05-10 20:21:17

+0

错字 - 每个'应该是'项目'。固定。 – tMC 2011-05-10 20:28:49