2

In Python 2.7, I can do this pass a parameter to an sql command like this:

cursor.execute("select * from my_table where id = %s", [2])

I can not get the array equivalent working like this:

cursor.execute("select * from my_table where id in %s", [[10,2]])

Obviously, I can just do string formatting, but I would like to do a proper parameter if possible. I'm using a postgresql database if that matters.

clay
  • 18,138
  • 28
  • 107
  • 192

1 Answers1

7
cursor.execute("select * from my_table where id = ANY(%s);", [[10, 20]])

See note. To use IN see section below.

cursor.execute(cursor.mogrify("select * from my_table where id in %s",
                              [tuple([10, 20])]))
f43d65
  • 2,264
  • 11
  • 15
  • The reason being that the `IN (1,2,3)` doesn't feature an array anywhere but rather a literal set of values. – Richard Huxton Jun 02 '15 at 10:42
  • For whoever happens to land here: I actually needed to add a comma after the list `...[tuple([10, 20],)...` to make it work. See also accepted answer here: https://stackoverflow.com/questions/8671702/passing-list-of-parameters-to-sql-in-psycopg2 – Anytoe Feb 01 '23 at 17:24