Creating Safe MySQL IN Clauses with Lists
When working with MySQL databases and Python, it can be useful to implode a list to use in an IN clause. However, it's essential to do this safely to prevent SQL injection vulnerabilities.
Instead of manually constructing a string containing the list of values, the preferred method is to use the query parameter mechanism. This allows you to pass the list directly to the database driver without having to handle any quoting or escaping.
Here's how you can accomplish this:
format_strings = ','.join(['%s'] * len(list_of_ids)) cursor.execute("DELETE FROM foo.bar WHERE baz IN (" + format_strings + ")", tuple(list_of_ids))
By using this method, you can avoid SQL injection by allowing MySQL to handle the parameterization of the query. The data will be inserted directly into the query without any preprocessing, ensuring both safety and efficiency.
The above is the detailed content of How to Safely Create MySQL IN Clauses with Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!