Re: How do I use parameterized queries with LIKE?

From: Daniele Varrazzo <daniele(dot)varrazzo(at)gmail(dot)com>
To: "W(dot) Matthew Wilson" <matt(at)tplus1(dot)com>
Cc: psycopg(at)postgresql(dot)org
Subject: Re: How do I use parameterized queries with LIKE?
Date: 2012-05-28 22:42:55
Message-ID: CA+mi_8bD6PNf3CYDA3geq=gTT3JVbB7z7kK485QkYD_Bpi00QQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

On Mon, May 28, 2012 at 11:00 PM, W. Matthew Wilson <matt(at)tplus1(dot)com> wrote:

> But when I move the "matt" part out and use a %s symbol instead, I get
> this error:
>
>    ValueError: unsupported format character ''' (0x27) at index 73
>
> What is the right solution here?

If you have parameters in the query, % is used as placeholder prefix.
You must use %% to include a literal % in the query:

In [14]: cur.execute("""select email_address from customer where
email_address like '%%' || %s || '%%'""", ('matt',))

or you can add the % to the value instead of the query:

In [17]: cur.execute("""select email_address from customer where
email_address like %s""", ('%matt%',))

Hope this helps,

-- Daniele

In response to

Responses

Browse psycopg by date

  From Date Subject
Next Message P. Christeas 2012-05-28 22:44:26 Re: How do I use parameterized queries with LIKE?
Previous Message Adrian Klaver 2012-05-28 22:13:27 Re: How do I use parameterized queries with LIKE?