Re: How do I use parameterized queries with LIKE?

From: Federico Di Gregorio <fog(at)dndg(dot)it>
To: psycopg(at)postgresql(dot)org
Subject: Re: How do I use parameterized queries with LIKE?
Date: 2012-05-29 06:28:58
Message-ID: 4FC46CAA.8030109@dndg.it
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

On 29/05/12 02:30, W. Matthew Wilson wrote:
> On Mon, May 28, 2012 at 6:42 PM, Daniele Varrazzo
> <daniele(dot)varrazzo(at)gmail(dot)com> wrote:
>> > 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%',))
> Thanks so much! I'm using the first solution, so that I can just
> extract user-submitted data and pass it right in, rather than
> prepending and appending '%' on the user data.

If you're using user-submitted data remember to ALWAYS use bound
variables and never fallback to Python string interpolation: SQL
injection lurks.

federico

--
Federico Di Gregorio federico(dot)digregorio(at)dndg(dot)it
Studio Associato Di Nunzio e Di Gregorio http://dndg.it
Gli avvoltoi cinesi si nutrono di arte, ma possono anche mangiare
i `domani'. -- Haruki Murakami

In response to

Browse psycopg by date

  From Date Subject
Next Message Brian Hamlin 2012-05-31 03:51:48 10.6 Mac build - Intel only
Previous Message W. Matthew Wilson 2012-05-29 00:30:31 Re: How do I use parameterized queries with LIKE?