【问题标题】:Error while passing variables to a sql query in python将变量传递给python中的sql查询时出错
【发布时间】:2020-04-03 09:45:41
【问题描述】:

我在 python 中使用 sql 查询。我想在查询中将一些值作为参数/变量传递。我见过几个相关的问题。我正在关注这些问题,但我不确定我哪里出错了。我的代码

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))

这给出了错误:

并非所有参数都在 SQL 语句中使用

我也尝试过使用 %s,但该方法也出现错误。有人可以帮助我如何正确传递变量吗?

【问题讨论】:

标签: python mysql sql mysql-connector-python


【解决方案1】:

使用%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

【讨论】:

    猜你喜欢
    • 2017-09-10
    • 2022-08-15
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    相关资源
    最近更新 更多