我是Python和Psycopg2的新手......我正在尝试使用IN
sql语句和其他WHERE
子句进行查询,但我收到的错误是这样的:< / p>
psycopg2.ProgrammingError: argument formats can't be mixed
根据我的理解,我将Python元组与字符串混合,这里是SELECT
语句:
cur2.execute("SELECT hash FROM jobsads_text\
WHERE\
date_inserted::timestamp::date - now()::timestamp::date <= 0\
AND date_inserted::timestamp::date - now()::timestamp::date >= -7\
AND hash NOT IN %s \
AND lower((%s)) LIKE '%(%s)%'\
ORDER BY date_inserted asc;", ((not_in_sql,), search_field, search_string))
我在上面的查询中收到错误。
此查询运行正常:
cur2.execute("SELECT hash FROM jobsads_text\
WHERE\
date_inserted::timestamp::date - now()::timestamp::date <= 0\
AND date_inserted::timestamp::date - now()::timestamp::date >= -7\
AND hash NOT IN %s \
ORDER BY date_inserted asc;", (not_in_sql,))
我的问题是......如何将元组not_in_sql
与字符串search_field
和search_string
混合使用?
任何线索?
最诚挚的问候,
答案 0 :(得分:2)
t = (1, 3)
search_field = 'c'
search_string = '%something%'
print cursor.mogrify("""\
select *
from p
where
c in %%s
and
lower (%s) like %%s
""" % search_field, (t, search_string))
将输出:
select *
from p
where
c in (1, 3)
and
lower (c) like '%something%'
psycopg2不会替换列名等标识符,因此在将查询作为方法的第一个参数传递之前必须替换。