Home >Backend Development >Python Tutorial >How Can I Safely Use a List of IDs in a MySQL IN Clause?
Imploding Lists for Secure MySQL IN Clauses
To safely use a list of IDs in a MySQL IN clause and avoid SQL injection, use MySQL's parameterization capabilities instead of manually imploding the list and escaping it yourself.
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 approach has several advantages:
Note that the data is passed as a tuple of values, which is safe for use in MySQL queries. The format_strings variable creates a comma-separated list of placeholders for the parameters.
The above is the detailed content of How Can I Safely Use a List of IDs in a MySQL IN Clause?. For more information, please follow other related articles on the PHP Chinese website!