IceSquad
IceSquad

Reputation: 23

Python - Psycopg2, how to mix tuples and strings in cur.execute()?

I'm new to Python and Psycopg2... I'am trying to do a query that uses IN sql statement and other WHERE clauses but I'm getting an error like this:

psycopg2.ProgrammingError: argument formats can't be mixed

From what I understand I'm mixing a Python tuple with strings, here is the SELECT statement:

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

I get error in the query above.

This query bellow runs 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,))

My question is... How can I mix the tuple not_in_sql with the strings search_field and search_string?

Any clues?

Best Regards,

Upvotes: 2

Views: 4193

Answers (1)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125284

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

Will output this:

select * 
from p
where 
    c in (1, 3)
    and
    lower (c) like '%something%'

psycopg2 will not substitute identifiers like column names so you must substitute then before passing the query as the first argument of the method.

Upvotes: 2

Related Questions