Python-游标-列表中的多个筛选器
我想运行一个查询,根据两个列表中的值筛选两列 基本上,我想模拟如下两个过滤器:Python-游标-列表中的多个筛选器,python,sql,list,filter,cursor,Python,Sql,List,Filter,Cursor,我想运行一个查询,根据两个列表中的值筛选两列 基本上,我想模拟如下两个过滤器: SELECT * FROM my_table WHERE customers in ("John","Peter") AND customers_numbers IN ('1','2') 但是customers和customers_number的值在两个列表中。为了尝试这一点,我编写了以下代码: list1 = ["John","Peter&qu
SELECT *
FROM my_table
WHERE customers in ("John","Peter") AND customers_numbers IN ('1','2')
但是customers和customers_number的值在两个列表中。为了尝试这一点,我编写了以下代码:
list1 = ["John","Peter"]
list2 = [1,2]
query_sql = "DELETE FROM vw_bill_details WHERE customers in (%s) and customers_numbers in (%s)" % ','.join(['?'] * len(list1)) % ','.join(['?'] * len(list2))
cursor.execute(query_sql, list1,list2)
但我得到了以下错误:
query_sql = "DELETE FROM vw_bill_details WHERE customers in (%s) and customers_numbers in (%s)" % ','.join(['?'] * len(list1)) % ','.join(['?'] * len(list2))
TypeError: not enough arguments for format string
如何使用python进行上述查询
谢谢 您的查询中有一个错误,两个术语之间有一个额外的
%
,而不是逗号。此外,当您对多个术语使用%
格式时,需要将整个变量部分放在括号中的%
后面:
query_sql = "DELETE FROM vw_bill_details WHERE customers in (%s) and customers_numbers in (%s)" % (','.join(['?'] * len(list1)), ','.join(['?'] * len(list2)))
改进:
query_sql = """DELETE FROM vw_bill_details
WHERE customers in (%s)
and customers_numbers in (%s)""" % (
','.join(['?'] * len(list1)), ','.join(['?'] * len(list2)))
str.join()
适用于任何iterable,包括字符串,因此','.join(['?']*len(list1))
部分可以写成','.join('?'*len(list1))
标记是单个字符串,而不是包含单个元素的列表
中的客户(“John”、“Peter”)和客户编号(“1”、“2”)
不关心/检查“John”是否有客户编号1或2。所以它可以和约翰-2和彼得-1匹配,而不是你想要的约翰-1和彼得-2
此处可以看到不匹配的示例:
您可以通过指定名称和编号来避免这种不匹配:
WHERE(客户='John'和客户编号='1')
或(客户='Peter'和客户编号='2')
也可以写为匹配对:
其中(客户,客户编号)=('John',1)
您还可以通过以下功能将其扩展为多个选项:
其中(('John',1),('Peter',2))中的(客户,客户编号)
与上面的扩展和/或版本相比,使用?
s参数化哪个更容易