2012-03-14 57 views
1

私はIN SQLステートメントおよびその他のWHERE句を使用するクエリを実行しようとPythonとPsycopg2 ... I'amに新たなんだけど、私は取得しています。このようなエラー:何からPython - Psycopg2、cur.execute()でタプルと文字列を混合する方法は?

psycopg2.ProgrammingError: argument formats can't be mixed 

I私は文字列で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)) 

私は上記のクエリでエラーが発生します。

このクエリ怒鳴るはOK走る:

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

関連する問題