gpt4 book ai didi

python - 使用 Python 将列表值传递给 MySQL 查询

转载 作者:行者123 更新时间:2023-12-01 06:44:42 26 4
gpt4 key购买 nike

我想将列表值与其他参数值一起传递。以下是我的场景。我想为“代码”列传递多个值,并希望将单个值传递给“大陆”列。

param = [('AFG', 'IND'),'Asia']
query = "select * from country where Code in (%s) AND Continent = %s"
cursor.execute(query,param)

在 Python 中执行时,出现以下错误。

Failed to execute Query: Failed processing format-parameters; Python 'tuple' cannot be converted to a MySQL type

最佳答案

这里的技巧是 WHERE IN 子句,它实际上不适合参数化。一个选项生成一个 IN 子句,其中包含列表中占位符的确切数量:

codes = ('AFG', 'IND')
continent = 'Asia'
params = codes + (continent,)
where_in = ','.join(['%s'] * len(codes))
sql = "SELECT * FROM country WHERE Code IN (%s) AND Continent = %s" % (where_in, '%s')
cursor.execute(sql, params)

要了解上面的脚本实际上做了什么,让我们看看各个部分:

print(where_in)
print(sql)

%s,%s
SELECT * FROM country WHERE Code IN (%s,%s) AND Continent = %s

这里的技巧是,我们实际上使用 %s 占位符两次,一次用于 Python 字符串,第二次用于 SQL 查询字符串。此外,我们绑定(bind)一个包含所有绑定(bind)值的单级元组:

('AFG', 'IND', 'ASIA')

关于python - 使用 Python 将列表值传递给 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59284244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com