python - 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'
如何让查询字符串正常工作?
解决方案
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,))
推荐阅读
- reactjs - Docker:单个容器内的多个服务,如何访问本地主机?
- java - 如何将数据从 Dropwizard 身份验证器传递回应用程序
- android - React Native Android 无法从本地加载 html 文件
- c# - 如何制作一个快速窗口来重命名选项卡
- c++ - C++如果一个类不能合成move构造函数,是否意味着move构造函数被删除了?
- docker - 我想在容器运行期间根据我传递的 env 变量运行脚本
- python-3.x - 如何从 Jenkins 获取参数到 python 脚本
- python - 如何使用正则表达式和 Python 将名称与可能的特殊字符匹配?
- string - VS Code Extension API - 替换文档中的字符串?
- python - 通过Python中的子类函数更改父变量