Home  >  Q&A  >  body text

Nesting a list within IN clause in Python MySQL

<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>
P粉781235689P粉781235689424 days ago458

reply all(2)I'll reply

  • P粉434996845

    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

    reply
    0
  • P粉212114661

    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.

    reply
    0
  • Cancelreply