【发布时间】:2020-05-08 18:02:24
【问题描述】:
我有一个 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'
如何让查询字符串正常工作?
【问题讨论】:
-
不要使用字符串连接,这就是导致问题的原因。再多的引用或转义都无法解决根本问题。改用参数
标签: python postgresql