Is there a way to pass a python list as a parameter of prepared statement in pymysql?
list_id = [1,2,3]
sql = "select * from table where id in (%s)"
cursor.execute(sql,(list_id,))
Is there a way to pass a python list as a parameter of prepared statement in pymysql?
list_id = [1,2,3]
sql = "select * from table where id in (%s)"
cursor.execute(sql,(list_id,))
I would do it this way.
list_id = [1,2,3]
sql = "select * from table where id in ({})".format(",".join([str(i) for i in list_id]))
print(sql)
Out[]: "select * from table where id in (1,2,3)"
Should you need an alternative way of running execution, here is another reference to doing many cursor execution through pyodbc
library. Hope it helps.
executemany(sql, *params)
Executes the same SQL statement for each set of parameters, returning None. The single params parameter must be a sequence of sequences, or a generator of sequences.
params = [ ('A', 1), ('B', 2) ] executemany("insert into t(name, id) values (?, ?)", params) This will execute the SQL statement twice, once with ('A', 1) and once with ('B', 2).
if your list will have only integers, then you will have to combine them with a ',' and pass as string.
list_id = [1,2,3]
# not working:
list_str = ', '.join(list_id)
# most likely:
list_str = ', '.join(map(str, list_id))
But much better way, preventing construction crazy statements is with https://www.python.org/dev/peps/pep-0249/#paramstyle or as mentioned in a duplicate answer above. )