Nesting a list within IN clause in Python MySQL
P粉781235689
2023-08-22 17:04:59
<p>I know how to map a list to a string: </p>
<pre class="brush:php;toolbar:false;">foostring = ",".join( map(str, list_of_ids) )</pre>
<p>I know I can put that string into an IN clause using: </p>
<pre class="brush:php;toolbar:false;">cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring))</pre>
<p>I need to implement the same functionality in a MySQL database in a safe way (avoiding SQL injection). In the above example, because foostring is not passed as a parameter to execute, it is vulnerable. I also have to do quoting and escaping outside of the MySQL library. </p>
<p> (There is a related SO question, but the answers listed there either don't work with MySQL databases or are vulnerable to SQL injection attacks.) </p>
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
Tested under
python2.7
andpymysql==0.7.11
passedUse directly
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.