I am trying to execute a sql query with a joined list as a parameter .
I already established a database connection and I want to have a query like:
SELECT * FROM MYDATABASE.MY_TABLE
WHERE ( name IN ('name1','name2') );
So I want to pass the list as a parameter , and the variable filters is the variable that has the right format stored , but not actually used.
The code that was supposed to do that is :
my_list = ['name1', 'name2']
filters = ",".join(("'{}'".format(key) for key in my_list))
q = sql.SQL('''SELECT * FROM MYDATABASE.MY_TABLE WHERE ( name IN ({}) );''')
.format(sql.SQL(', ')
.join(sql.Placeholder() * len(my_list)))
cur = self.con.cursor()
query = q.as_string(context=self.con)
cur.execute(q)
results = cur.fetchall()
cur.close()
The string query is :
'SELECT * FROM MYDATABASE.MY_TABLE WHERE ( name IN (%s, %s) );'
, which seems right.
But there is an error bout the the escape character and I cannot find a way around.
Last , I have to use the placeholder and not a simple
".... where name = {}".format()
solution , mostly for security reasons.
Any help ?
EDIT:
I tried all the suggestions and they all give me the Syntax Error :
'ERROR: syntax error at or near ","
LINE 1: ....MY_TABLE WHERE (name IN (?,?)) ...
..................................................................... ^'