P粉4349968452023-08-23 15:50:40
Although this question is old, I wanted to leave a reply in case anyone else is also looking for what I'm looking for
The accepted answer gets confusing when we have a lot of parameters or want to use named parameters
After some attempts
ids = [5, 3, ...] # id列表 cursor.execute(''' SELECT ... WHERE id IN %(ids)s AND created_at > %(start_dt)s ''', { 'ids': tuple(ids), 'start_dt': '2019-10-31 00:00:00' })
Tested under python2.7
and pymysql==0.7.11
passed
P粉2121146612023-08-23 00:26:09
Use directlylist_of_ids
:
format_strings = ','.join(['%s'] * len(list_of_ids)) cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings, tuple(list_of_ids))
This way you can avoid quoting yourself and avoid various SQL injection problems.
Please note that the data (list_of_ids
) is passed directly to mysql's driver as a parameter (not in the query text), so there are no injection issues. You can keep any characters in the string without removing or quoting characters.