Python - Psycopg2,如何在cur.execute()中混合元组和字符串?

时间:2012-03-14 20:54:57

标签: python postgresql psycopg2

我是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_fieldsearch_string混合使用?

任何线索?

最诚挚的问候,

1 个答案:

答案 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不会替换列名等标识符,因此在将查询作为方法的第一个参数传递之前必须替换。