Skip to content

Instantly share code, notes, and snippets.

@romainnorberg
Last active January 30, 2023 19:36
Show Gist options
  • Save romainnorberg/2bc3d86237ee81b79639a33ff73d5b06 to your computer and use it in GitHub Desktop.
Save romainnorberg/2bc3d86237ee81b79639a33ff73d5b06 to your computer and use it in GitHub Desktop.

Revisions

  1. romainnorberg revised this gist Jul 14, 2020. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions readme.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    Blog post: https://blog.romainnorberg.be/post/python-avoid-sql-injection-when-using-mysqlcursor-execute
  2. romainnorberg revised this gist May 17, 2020. No changes.
  3. romainnorberg created this gist May 17, 2020.
    28 changes: 28 additions & 0 deletions python_mysql_avoid_injection.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    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 ✋