Home > Article > Backend Development > How to Safely Insert Lists into MySQL IN Clauses?
Insert Lists Safely into MySQL IN Clauses
This article explores an efficient and secure method for inserting lists into IN clauses within MySQL databases. While the traditional approach involves mapping lists to strings and inserting them directly, this method poses a risk of SQL injection due to the need for manual quoting and escaping.
To avoid this vulnerability, a safer approach is to use the list directly as a parameter in the MySQL query. The following code demonstrates this method:
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 code accomplishes the following:
It's important to note that this method relies on the MySQL driver's ability to handle parameters securely. As long as the data is passed correctly as a parameter, the query remains safe from SQL injection.
The above is the detailed content of How to Safely Insert Lists into MySQL IN Clauses?. For more information, please follow other related articles on the PHP Chinese website!