I'm trying to demonstrate how SQL injection attacks work in a class as a presentation.
I have the following piece of code in Python:
def query(username, password):
with mysql.connector.connect(**DB_INFO) as conn:
with conn.cursor() as cursor:
cursor.execute(f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}';")
res = cursor.fetchall()
conn.commit()
return res
The logic works by querying the database with a specific username and password. If the database returns a non-empty list, a user with that specific username and password exists.
But I also need to commit to the database, so for instance when the attacker injects a SQL DELETE FROM users; command in the username or password fields, the command takes effect.
But when I run the function with username: a and password: a'; DELETE FROM users; --, I get the following exception:
_mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now
Is there a way to fix this? Or should I change my code completely to have a function for querying and another function for modifying the database?