Blog post: https://blog.romainnorberg.be/post/python-avoid-sql-injection-when-using-mysqlcursor-execute
Last active
January 30, 2023 19:36
-
-
Save romainnorberg/2bc3d86237ee81b79639a33ff73d5b06 to your computer and use it in GitHub Desktop.
(Python) Avoid SQL injection when using MySQLCursor.execute()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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