I’m trying to execute a postgres select query using cursor.execute
. How can I write the query if the number of parameters change dynamically.
E.g
One instance the query can be
cursor.execute('SELECT name FROM personal_details WHERE id IN (%s, %s)', (3, 4))
an in some other instance the query can be
cursor.execute('SELECT name FROM personal_details WHERE id IN (%s, %s, %s)', (3, 4, 5))
If the parameters are available in a list as ids = [3, 4]
or ids = [3, 4, 5]
what is the proper way of writing this query
I tried with the following code
cursor.execute("SELECT name FROM personal_details WHERE id IN param = %s", [ids['param']])
But it returned with an error saying TypeError: list indices must be integers or slices, not str
2
Answers
You will need to build your statement dynamically:
Output of print:
You need to use ANY and psycopg2 list adaption: