python中传递多个参数

pdsfdshx  于 2021-07-27  发布在  Java
关注(0)|答案(2)|浏览(306)

我尝试将两个参数传递到sql语句中,如下所示:

cursor.execute(f"""select * from table 
                   where product_name = '{prod_name}' and date = '{sale_date}'"""")

我试着让这几个组合通过一个循环运行,所以我试着看看我如何可以有相应的改变。

prod_name = ['prod_a','prod_b']
sale_date = ['2020-01-01','2020-02-01']

我知道如何通过循环传递一个参数,但我不知道如何同时传递多个参数。

hec6srdp

hec6srdp1#

直接向sql查询中添加变量是一种安全隐患。 cursor.execute 只要将参数作为函数调用的第二个参数传递,就提供清理。
例子:

cursor.execute("select * form table where product_name = '%s' and date = '%s'", (prod_name, sale_date))

要一次遍历多个列表,可以执行以下操作(假设列表具有相同数量的值):

for i in range(len(prod_name)):
    cursor.execute("select * form table where product_name = '%s' and date = '%s'", (prod_name[i], sale_date[i]))

通过在一个范围内循环,我得到了0-len(prod\u name)的数字,当我循环索引 i 我可以用它来检索两个列表中的第一项。
山姆·梅森对使用 zip 组合迭代器的函数,可以这样使用:

for args in zip(prod_name, sale_date):
    cursor.execute("select * form table where product_name = '%s' and date = '%s'", args)
hgqdbh6s

hgqdbh6s2#

试试这个:

results = ()

dc = ['103,4770634', '42,427752', '64,10122045', '42,13603629', '42,25516425', '103,2748102', '42,1966402', '42,30262834', '42,6667711', '18,13737683', '42,28921168', '42,26076925', '103,3733654', '42,23313527', '64,3307344', '103,3973533', '42,6360982', '48,11846077', '103,3775309', '64,10122050', '42,1965119', '103,4265810', '103,3971645', '103,4962583', '103,689615', '42,22834366', '103,761655', '95,1184', '64,9594482', '42,22855603', '48,8654764', '103,4226756', '42,23366982', '103,3897036', '42,11339650', '101,6369', '42,25830920', '103,5009291', '42,29238961', '59,6299475', '42,22931663', '42,25839056', '43,11864458', '43,41346192', '103,4261645', '42,3747082', '103,4795050', '42,9417503', '103,4245623', '42,61431911']

try:
    sql = "SELECT * FROM tbl1 WHERE id1 in (%s) AND id2 in (%s)"
    in_ids = ', '.join(map(lambda x: '%s', dc))
    in_ids = in_ids % tuple(dc)
    sql = sql % (in_ids, in_ids)
    cursor.execute(sql)
    res = cursor.fetchall()
    results = results + res
except Exception, e:
    print e

相关问题