Skip site navigation (1) Skip section navigation (2)

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 (view raw or flat)
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

psycopg by date

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

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group