首页 > 解决方案 > SQL 字符串出错:“连接到 PostgreSQL 运算符时出错:日期 = 整数”

问题描述

我有一个应该每天早上运行的 Python(3) 脚本。在其中,我调用了一些 SQL。但是我收到一条错误消息:

连接到 PostgreSQL 运算符时出错不存在:日期 = 整数

SQL 基于字符串的连接:

ecom_dashboard_query = """
with 
days_data as (
select 
    s.date,
    s.user_type,
    s.channel_grouping,
    s.device_category,
    sum(s.sessions) as sessions,
    count(distinct s.dimension2) as daily_users,
    sum(s.transactions) as transactions,
    sum(s.transaction_revenue) as revenue
from ga_flagship_ecom.sessions s
where date = """ + run.start_date + """
group by 1,2,3,4
)

insert into flagship_reporting.ecom_dashboard
select *
from days_data;
"""

这是完整的错误:

09:31:25  Error while connecting to PostgreSQL  operator does not exist: date = integer
09:31:25  LINE 14: where date = 2020-01-19
09:31:25                      ^
09:31:25  HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

我尝试run.start_date像这样在 str 中包装:str(run.start_date)但我收到了相同的错误消息。

我怀疑这可能与我连接 SQL 查询字符串的方式有关,但我不确定。

查询直接在 SQL 中运行良好,带有硬编码日期且没有连接:

where date = '2020-01-19'

如何让查询字符串正常工作?

标签: pythonpostgresql

解决方案


cursor.execute将查询参数传递给方法会更好。来自文档

警告永远,永远,永远不要使用 Python 字符串连接 (+) 或字符串参数插值 (%) 将变量传递给 SQL 查询字符串。甚至在枪口下也没有。

因此,不要将字符串连接传递run.start_datecursor.execute.

在您的查询而不是串联使用%s

where date = %s
group by 1,2,3,4

在您的 python 代码中,将第二个参数添加到execute方法中:

cur.execute(ecom_dashboard_query , (run.start_date,))

推荐阅读