MySQL查询上的Python字符串格式

时间:2018-02-12 16:10:03

标签: mysql python-2.7

我尝试使用两个参数执行查询,一个是列表,另一个是数字。

这是我的代码:

cursor.execute("SELECT cod_art, price_EU, price_third_country 
                FROM lt_gamma_articles 
                WHERE cod_art in (%s) AND cod_store = %d 
                ORDER BY cod_art, timestamp" 
             % format_strings, tuple(cod_art_int), int(shop) )

我收到此错误:

TypeError:格式字符串

的参数不足

我认为错误在于字符串格式,但我不知道如何正确格式化它并且我已经卡住了一段时间。

1 个答案:

答案 0 :(得分:1)

从代码的外观来看,我正在基于imploding a list for use in a python MySQLDB IN clause来支持你。假设是这样,并且 format_strings 的构建类似于:

format_strings = ','.join(['%s'] * len(cod_art_int))

我会使用.format来构建查询字符串,并为位置查询参数建立一个列表:

query_params = list(cod_art_int)
query_params.append(int(shop))

query_sql = """
  SELECT cod_art, price_EU, price_third_country 
  FROM lt_gamma_articles
  WHERE cod_art IN ({cod_art_list}) AND cod_store = %s 
  ORDER BY cod_art, timestamp
""".format(cod_art_list=format_strings)

cursor.execute(query_sql, query_params)

说明:

Say cod_art_int是这个整数值列表:

cod_art_int = [10, 20, 30]

要在查询的cod_art IN (...)部分中使用这些值,您需要为每个值添加%s。这是通过以下方式完成的:

format_strings = ','.join(['%s'] * len(cod_art_int))

可以分解为:

step_one = ['%s'] * len(cod_art_int)
# ['%s', '%s', '%s']

format_strings = ','.join(step_one)
# '%s,%s,%s'

构建最终查询字符串时,将{cod_art_list}替换为format_strings

query_sql = """
    SELECT cod_art, price_EU, price_third_country 
    FROM lt_gamma_articles
    WHERE cod_art IN ({cod_art_list}) AND cod_store = %s 
    ORDER BY cod_art, timestamp
""".format(cod_art_list=format_strings)

你得到了查询字符串:

SELECT cod_art, price_EU, price_third_country 
FROM lt_gamma_articles
WHERE cod_art IN (%s,%s,%s) AND cod_store = %s 
ORDER BY cod_art, timestamp

然后在查询中安全地替换您的查询参数以替换%s。您构建参数列表以对应%s s。由于cod_art IN (%s,%s,%s)是第一个,您首先将其添加到列表中,然后是cod_storeint(shop)的值,我要说的是456):

query_params = list(cod_art_int)
# [10, 20, 30] 

query_params.append(int(shop))
# [10, 20, 30, 456] 

最后,使用其参数执行查询:

cursor.execute(query_sql, query_params)