从python列表中删除MYSQL中包含信息的多行
如果列表LL:从python列表中删除MYSQL中包含信息的多行,python,mysql,string,sql-delete,Python,Mysql,String,Sql Delete,如果列表LL: LL=['foo',bar','noo','boo',] 在MySQL表中,使用其他ID在列ID中进行测试 我可以使用以下命令删除LL中ID为的所有行: csr.execute("""DELETE FROM test.test WHERE ID = "Foo"; """) csr.execute("""DELETE FROM test.test WHERE ID = "bar"; """) csr.execute("""DELETE FROM test.test W
LL=['foo',bar','noo','boo',]
在MySQL表中,使用其他ID在列ID中进行测试
我可以使用以下命令删除LL中ID为的所有行:
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"; """)
我怎么能按程序做呢 字符串格式化程序-
然后运行列表中的每个SQL语句
for item in LL:
csr.execute("DELETE FROM test.test WHERE ID = '%s'", item)
像这样吗?只需一个查询即可:
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注入是安全的。我们可以使用一个删除查询并将列表转换为元组
list_ids = ['foo', bar', 'noo', 'boo',]
delete_query = "DELETE FROM test.test WHERE ID=%s"
delete_records = tuple(list_ids)
cursor.executemany(delete_exec, delete_records)
对于MySQL,您需要使用
%s
而不是?
作为参数标记。别忘了承诺
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()
打字错误-
每个
都应该是项
。修复。否,请查看答案中的查询字符串表示“where id in…”而不是“where id=…”@user428862“in('abc','hjk',…)”在MySQL中的工作方式。它优先于“where id='abc'或id='hjk'”。但是,我的示例包含语法错误和数字ID。请尝试更新的版本。id_list=['acb','def',]SQL包含0个参数标记,但提供了2个参数“您需要按照指定构造查询字符串变量”。它将每个id替换为%s。打印查询\u str“从测试中删除,其中id在(%s,%s)中,LL
仅包含受信任的项,这一点至关重要。如果它包含来自不受信任源的数据,且未正确转义,则可以进行SQL注入。
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()