Executing “SELECT … WHERE … IN …” using MySQLdb

后端 未结 10 1997
耶瑟儿~
耶瑟儿~ 2020-11-29 21:23

I\'m having a problem executing some SQL from within Python, despite similar SQL working fine from the mysql command-line.

The table looks like this:

10条回答
  •  自闭症患者
    2020-11-29 22:02

    Here is a similar solution which I think is more efficient in building up the list of %s strings in the SQL:

    Use the list_of_ids directly:

    format_strings = ','.join(['%s'] * len(list_of_ids))
    cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings,
                    tuple(list_of_ids))
    

    That way you avoid having to quote yourself, and avoid all kinds of sql injection.

    Note that the data (list_of_ids) is going directly to mysql's driver, as a parameter (not in the query text) so there is no injection. You can leave any chars you want in the string, no need to remove or quote chars.

提交回复
热议问题