MySQL查询中的Python字符串格式
我尝试使用两个参数执行查询,一个是列表,另一个是数字 这是我的密码:MySQL查询中的Python字符串格式,mysql,python-2.7,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"
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:格式字符串的参数不足
我认为错误在于字符串格式,但我不知道如何正确设置格式,我已经被困了一段时间。从您的代码外观上看,我正在使用您的代码。假设是这样的话 格式字符串的构建类似于:
format_strings = ','.join(['%s'] * len(cod_art_int))
我将使用来构建查询字符串,并构建位置查询参数的列表:
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)
cursor.execute(query_sql, query_params)
说明: 假设
cod\u art\u int
是整数值列表:
cod_art_int = [10, 20, 30]
为了在查询的(…)部分中使用这些值,您需要为每个值添加一个%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\u art\u list}
替换为格式字符串
:
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)
然后得到查询字符串:
选择商品、价格、第三国
从lt_gamma_文章
其中,货到付款(%s,%s,%s)和货到付款存储=%s
按货到付款、时间戳订购
然后,您的查询参数将在查询中被安全地替换,以替换%s
s。您可以建立与%s
s相对应的参数列表。因为cod\u art IN(%s,%s,%s)
是第一个,所以您首先将其添加到列表中,然后是cod\u store的值(int(shop)
,我要说的是456):
最后,使用查询的参数执行查询:
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)
cursor.execute(query_sql, query_params)
答对 了成功了!非常感谢你!你有没有像链接之类的消息来源让我明白这一点?@AlbertS。我没有一个好的链接,但是看到我的更新答案。