繁体   English   中英

SQL 字符串错误:“连接到 PostgreSQL 运算符时出错不存在:日期 = 整数”

[英]Error with SQL string: "Error while connecting to PostgreSQL operator does not exist: date = integer"

我有一个应该每天早上运行的 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'

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

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

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

因此,而不是字符串连接传递run.start_date作为cursor.execute的第二个参数。

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

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

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

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

你的句子是错误的:

其中日期 = """ + run.start_date + """

尝试比较日期和字符串,这是不可能的,您需要将“run.start_date”转换为日期时间并进行简单比较:

date_format = datetime.strptime(your_date_string, '%y-%m-%d')

并将此日期转换为日期时间:

where date = date_format

最终代码:

date_format = datetime.strptime(your_date_string, '%y-%m-%d')
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 = {}
group by 1,2,3,4
)

insert into flagship_reporting.ecom_dashboard
select *
from days_data;
""".format(date_format)

暂无
暂无

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

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