Handling a dynamic sql query in Psycopg2 with multiple WHERE condition

58 Views Asked by At

I want to execute a sql query dynamically with multiple WHERE conditions. the query is as below

query = """SELECT * FROM UBO_EXCEPTION
WHERE reg_nb = %s
AND   return_date = %s::date
AND   data_type = %s
ORDER BY db_timestamp
LIMIT 1"""

The method that run the query is as below:

cursor.execute(query, param)
result = cursor.fetchall()

Sample param value is as below, there are 4 records in it:

(('00246102', datetime.date(2024, 3, 25), 'UKNI'), ('00246107', datetime.date(2024, 3, 25), 'SH01'), ('00246109', datetime.date(2024, 3, 25), 'CS01'), ('00246101', datetime.date(2024, 3, 25), ''))

This is giving an error:- not all arguments converted during string formatting.

I tried a minor change in the method, which is as below:

cursor.execute(query, (param,))
result = cursor.fetchall()

This gave me:- tuple out of index error

I am not sure, what to do next. Any suggestion is welcomed. Thank you.

0

There are 0 best solutions below