2012-03-14 162 views
1

我是新來的Python和Psycopg2 ...我'嘗試這樣做,使用IN SQL語句和其他WHERE子句的查詢,但我發現這樣的錯誤:Python - Psycopg2,如何在cur.execute()中混合元組和字符串?

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,)) 

我的問題是...我怎麼能與琴絃search_fieldsearch_string混合元組not_in_sql

任何線索?

最好的問候,

回答

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不會取代像列名標識,所以你必須傳遞查詢作爲方法的第一個參數之前替換即可。

+0

太棒了!這是工作!非常感謝您的幫助。 – IceSquad 2012-03-17 15:19:46

相關問題