简体   繁体   English

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

[英]Pass list values to MySQL query using Python

I want to pass list values along with other parameter values.我想将列表值与其他参数值一起传递。 following is my scenario.以下是我的场景。 I want to pass multiple values for column "Code" and want to pass single value to "Continent" column.我想为“代码”列传递多个值,并想将单个值传递给“大陆”列。

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

while executing in Python, I am getting following error.在 Python 中执行时,出现以下错误。

Failed to execute Query: Failed processing format-parameters; Failed to execute Query:处理格式参数失败; Python 'tuple' cannot be converted to a MySQL type Python 'tuple' 无法转换为 MySQL 类型

The trick here is the WHERE IN clause, which isn't really amenable to being parameterized.这里的技巧是WHERE IN子句,它并不真正适合参数化。 One option generates an IN clause with the exact number of placeholders in your list:一个选项会生成一个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)

To see what the above script actually did, lets look at the various parts:要了解上面的脚本实际做了什么,让我们看看各个部分:

print(where_in)
print(sql)

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

The trick here is that we actually use a %s placeholder twice , once for the Python string, and a second time for the SQL query string.这里的技巧是我们实际上使用了两次%s占位符,一次用于 Python 字符串,第二次用于 SQL 查询字符串。 Also, we bind a single level tuple containing all bound values:此外,我们绑定一个包含所有绑定值的单级元组:

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

first you split the list and then you split the tuple.首先拆分列表,然后拆分元组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM