Securing MySQL Queries in Python to Prevent SQL Injection
When querying MySQL databases from Python, preventing SQL injection attacks is crucial. This involves ensuring that user-provided variables don't interfere with the query structure.
Execute parameterized queries using the "execute" function with %s as placeholders for variables. Pass the variables as a list or tuple as the second parameter to execute.
c = db.cursor() max_price = 5 c.execute("SELECT spam, eggs, sausage FROM breakfast WHERE price < %s", (max_price,))
Avoid direct string substitution using %. Instead, use a comma as the placeholder:
c.execute("SELECT spam, eggs, sausage FROM breakfast WHERE price < %s", (max_price,))
Do not enclose the placeholder with single quotes if the parameter is a string:
c.execute("SELECT spam, eggs, sausage FROM breakfast WHERE price < %s", (max_price,))
By following these best practices, you can reduce the risk of SQL injection attacks and ensure the security of your MySQL connections in Python.
The above is the detailed content of How Can I Secure MySQL Queries in Python Against SQL Injection?. For more information, please follow other related articles on the PHP Chinese website!