How to Prevent SQL Injection in Python Web Applications
This article explains why SQL injection occurs in Python web development, demonstrates vulnerable code using string concatenation, shows the resulting errors, and provides two effective solutions—input escaping and MySQLdb's parameterized queries—to secure your applications.
SQL injection remains the top web vulnerability, especially when using relational databases in backend development. This article explains how SQL injection can occur in Python web applications and demonstrates it with a simple class that builds SQL statements via string concatenation.
Cause
The most common cause is direct string concatenation of user input into SQL queries. Even using placeholders like %s without proper parameter binding does not prevent injection.
Vulnerable Example
A method constructs a SELECT query by concatenating the user‑controlled testUrl value, allowing an attacker to append a single quote and trigger a syntax error, confirming the injection point.
Running the script yields an error such as:
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''t.tips''' at line 1")Solution
Two approaches are recommended:
Escape or encode user input before inclusion in SQL.
Use the parameterized query support provided by Python’s MySQLdb module (or similar libraries).
By modifying the class to use parameterized execution, the SQL statement and its parameters are passed separately, and the driver safely escapes the values.
Example:
preUpdateSql = "UPDATE `article` SET title=%s, date=%s, mainbody=%s WHERE id=%s"
mysql.insert(preUpdateSql, [title, date, content, aid])This prevents injection because the driver handles escaping of the supplied list of values.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
