简体   繁体   English

Python为MySQL创建动态选择语句

[英]Python create dynamic select statement for mysql

In my MySQL database I have 10 tables. 在我的MySQL数据库中,我有10个表。 Based on the user input, I want to select the rows from one of the table. 根据用户输入,我想从表之一中选择行。 The user input is an image. 用户输入是图像。 I am getting the number of columns and rows of pixels the image has and storing it in a variable. 我正在获取图像具有的像素列和行数,并将其存储在变量中。

rows,cols,channels = img.shape
w = int(cols)
h = int(rows)
l = w-10
m = w+10
p = h-10
q = h+10
area = w*h

the mysql tables are created basis the area of the image, and hence, depending on the area, I want to select the values from a specific table. mysql表是根据图像的区域创建的,因此,根据该区域,我想从特定表中选择值。

if (area < 110980):
        sql = "select * from adf1 where WIDTH between %s and %s and HEIGHT between %s and %s;",(l,m,p,q)
    elif (area < 182520):
        sql = "select * from adf2 where WIDTH between %s and %s and HEIGHT between %s and %s;",(l,m,p,q)
else:
        sql = "select * from adf10 where WIDTH between %s and %s and HEIGHT between %s and %s;",(l,m,p,q)
cur = mysql.connect().cursor()
cur.execute(sql)

I am getting the following error: 我收到以下错误:

TypeError: cannot concatenate 'str' and 'tuple' objects

However, when I pass on a single query within cur.execute I am able to retrieve the results. 但是,当我在cur.execute传递单个查询时,我可以检索结果。

cur.execute("select * from adf10 where WIDTH between %s and %s and HEIGHT between %s and %s;",(l,m,p,q))

current your variable sql is tuple, so if you want to pass it as parameters to the execute you should use * 当前您的变量sql是元组,因此如果要将其作为参数传递给execute ,则应使用*

cur.execute(*sql)

you can read more in the doc unpacking-argument-lists 您可以在doc unpacking-argument-list中阅读更多内容

this should fix your problem. 这应该可以解决您的问题。 You need to use % not comma in the queries inside if else. 如果不是,则需要在内部查询中使用% not逗号。

"select * from adf2 where WIDTH between %s and %s and HEIGHT between %s and %s;"%(l,m,p,q)

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

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