From: | Israel Ben Guilherme Fonseca <israel(dot)bgf(at)gmail(dot)com> |
---|---|
To: | Sukhbir Singh <singheinstein(at)gmail(dot)com> |
Cc: | psycopg(at)postgresql(dot)org |
Subject: | Re: Unpacking a Python list in a query. |
Date: | 2011-06-24 19:25:02 |
Message-ID: | BANLkTin5xdmFG_ua3TQPbQa_EwYKShcR6w@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | psycopg |
"UPDATE foobartable SET name = 'FooBar' WHERE name in (%s)"
And pass your list as a parameter (it must be a tuple).
execute("UPDATE foobartable SET name = 'FooBar' WHERE name in (%s)",
(tuple(yourlist),))
That should work.
2011/6/24 Sukhbir Singh <singheinstein(at)gmail(dot)com>
> Hi,
>
> I am using the psycopg2 adapter on Python 2.6.
>
> There was a requirement to automate certain UPDATE queries, so I
> designed the program in such a way that the end of the queries are in
> a list. I will illustrate with an example.
>
> The query is:
>
> UPDATE foobartable SET name = 'FooBar' WHERE name = %s OR name = %s
>
> And say I have a list:
>
> ["Foo", "Bar"]
>
> So, I want to execute the complete query as: substituting element by
> element from the list for each %s:
>
> UPDATE foobartable SET name = 'FooBar' WHERE name = 'Foo' OR name =
> 'Bar'
>
> The question is: how do I pass this list to the query?
>
> I tried using the format method and list unpacking (*list) and it
> works. But the docs recommend otherwise: "Warning Never, never, NEVER
> use Python string concatenation (+) or string parameters interpolation
> (%) to pass variables to a SQL query string. Not even at gunpoint"
> This is what I did:
>
> curr.execute("UPDATE foobartable SET name='FooBar' WHERE
> name='{0}' or name='{1}';".format(*list))
>
> ... which I am certain is wrong.
>
> How can I get this working with something safe and the recommended way
> of doing it?
>
> --
> Sukhbir.
>
> --
> Sent via psycopg mailing list (psycopg(at)postgresql(dot)org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/psycopg
>
From | Date | Subject | |
---|---|---|---|
Next Message | Sukhbir Singh | 2011-06-24 19:35:13 | Re: Unpacking a Python list in a query. |
Previous Message | Sukhbir Singh | 2011-06-24 19:05:08 | Unpacking a Python list in a query. |