Skip to content

Instantly share code, notes, and snippets.

@romainnorberg
Last active January 30, 2023 19:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainnorberg/2bc3d86237ee81b79639a33ff73d5b06 to your computer and use it in GitHub Desktop.
Save romainnorberg/2bc3d86237ee81b79639a33ff73d5b06 to your computer and use it in GitHub Desktop.
(Python) Avoid SQL injection when using MySQLCursor.execute()
import mysql.connector as mdb
con = mdb.connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='rootroot',
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