SecPrep logoSecPrep

Review this query builder. What's the vulnerability and how do you fix it?

Vulnerable code

python
def get_user(conn, username):
    q = "SELECT * FROM users WHERE username = '" + username + "'"
    return conn.execute(q).fetchone()
SQL Injection

Fixed

python
def get_user(conn, username):
    q = "SELECT * FROM users WHERE username = %s"
    return conn.execute(q, (username,)).fetchone()

User input is concatenated directly into the SQL string, allowing SQL injection. Fix with a parameterized/prepared statement so the driver separates code from data. Never build SQL by string concatenation of untrusted input.

Practice this in the app →