带变量但不使用%s的python SQL语句

2024-04-25 00:48:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望我能把我的问题说清楚。谢谢:)

我正在使用impala连接(库:从黑斑羚.dbapi导入连接)。你知道吗

为了运行查询,我使用了execute命令: cursor.execute(query.value, (year_var, month_var,day_var))

一般来说,它工作得很好,也适用于变量。当我使用类似SQL的语句时,问题就开始了(例如,'%seo'——其中包含%s)。你知道吗

第一个论点(查询.值)是字符串:

create table bi_db.search_terms as
select search_query,search_contain,count(*) searches
from (
select  search_query,
case when lower(search_query) like '%logo%' then 'logo'
     when lower(search_query) like '%google%' then 'google'
     when lower(search_query) like '%facebook%' then 'facebook'
     when lower(search_query) like '%instagram%' then 'instagram'
     when lower(search_query) like '%etsy%' then 'etsy'
     when lower(search_query) like '%seo%' then 'seo'
     when lower(search_query) like '%social media%' then 'social media'
     else 'else' end as search_contain
from traffic_db.traffic_parq   a
where year = %s AND month = %s AND day = %s AND  controller = 'search'  and action in ('gigs','users')        
and search_query is not null and search_query<>'' ) t
group by search_query,search_contain

第二个论点游标.执行(例如(年变量、月变量、日变量))指我在运行的查询中放入的%s,以便使用动态变量。你知道吗

**问题是python认为它有5个参数,而不是只有3个。这是因为我有%seo%social在LIKE语句中**

有人遇到过这种问题吗?知道怎么解决吗?你知道吗

非常感谢!你知道吗


Tags: andseoexecutesearchvarsocialqueryyear
1条回答
网友
1楼 · 发布于 2024-04-25 00:48:34

您可以在查询中转义文字百分号(例如%%seo%%),不过将模式作为参数传递给execute()也会更干净:

sql = """
create table bi_db.search_terms as
select search_query,search_contain,count(*) searches
from (
select  search_query,
case when lower(search_query) like %s then 'logo'
...
"""
cursor.execute(sql, ('%logo%', ...))

相关问题 更多 >