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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3