将变量传递给 python 中的 sql 查询时出错

Error while passing variables to a sql query in python

我正在 python 中使用 sql 查询。我想在查询中将一些值作为 parameters/variables 传递。我看到的相关问题很少。我正在关注这些问题,但我不确定我哪里出错了。我的代码

import mysql.connector

floor = 'L2'
cursor.execute ("""SELECT t1.deviceId, t1.date, t1.vavId, t1.timestamp, t1.nvo_airflow , t1.nvo_air_damper_position , t1.nvo_temperature_sensor_pps
                   FROM
                       (SELECT deviceId, date, nvo_airflow, nvo_air_damper_position, nvo_temperature_sensor_pps, vavId, timestamp, counter from vavData where date='2019-12-10' and floor=?1) t1
                   INNER JOIN
                        (SELECT date,max(timestamp) as timestamp,vavId from vavData where date='2019-12-10' and floor=?2 group by vavId) t2
                   ON (t1.timestamp = t2.timestamp) """,(floor,floor))

这给出了错误:

Not all parameters were used in the SQL statement

我也尝试过使用 %s,但我也遇到了错误。有人可以帮助我如何正确传递变量吗?

使用%s参数标记,让你的查询变成

>>> q="""SELECT t1.deviceId, t1.date, t1.vavId, t1.timestamp, t1.nvo_airflow , t1.nvo_air_damper_position , t1.nvo_temperature_sensor_pps
                        FROM
                            (SELECT deviceId, date, nvo_airflow, nvo_air_damper_position, nvo_temperature_sensor_pps, vavId, timestamp, counter from vavData where date='2019-12-10' and floor=%s) t1
                        INNER JOIN
                             (SELECT date,max(timestamp) as timestamp,vavId from vavData where date='2019-12-10' and floor=%s group by vavId) t2
                        ON (t1.timestamp = t2.timestamp) """

>>> cursor.execute(q,('xxxx', 'xxxx'))

现在只需 运行,如预期的那样 python 3.7mysql.connector.version.VERSION (8, 0, 18, '', 1)

勾选this answer also