[Python][MySQL] Injecting raw variables directly into the SQL string

 Injecting raw variables directly into the SQL string

When working with SQL in Python using libraries like pymysql or mysql-connector, a common mistake is injecting raw variables directly into the SQL string.

user_email = "abc@gmail.com"
query = f'SELECT * FROM user_info WHERE USER_EMAIL = "{user_email}"'
cursor.execute(query)

For string interpolation, f-string was used along with "" to escape special characters. This would break the SQL query due to the special character, '@'. 

SELECT * FROM user_info WHERE USER_EMAIL = "abc"@gmail.com"

This direct injection could cause a worse issue, security-wise.

If a user passes something like this, it would remove the table.
user_email = '"; DROP TABLE user_info; --'

Solution

Use parameterized queries

query = 'SELECT * FROM user_info WHERE USER_EMAIL = %s'
cursor.execute(query, (user_email,))


Comments