Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
(Python) Avoid SQL injection when using MySQLCursor.execute()
import mysql.connector as mdb
con = mdb.connect(
db='db', charset='utf8'
cur = con.cursor(dictionary=True)
# Injection work using cursor.execute(sql)
id = '1 OR 1=1'
cur.execute("SELECT * FROM user WHERE id=%s" % (id,))
result = cur.fetchall()
print("%d results !" % len(result)) # X results !
# Injection doesn't work using cursor.execute(sql, (val1, val2))
id = '1 OR 1=1'
cur.execute("SELECT * FROM user WHERE id=%s", (id,))
result = cur.fetchall()
print("%d result ✋" % len(result)) # 1 result ✋
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.