May 17th 2020

(Python) Avoid SQL injection when using MySQLCursor.execute()

Original post: dev.to/romainnorberg/python-avoid-sql-injection-when-using-mysqlcursor-execute-4dn0


Don't do

sql = "SELECT * FROM user WHERE id=%s" % (id,)
cursor.execute(sql)

Do

sql = "SELECT * FROM user WHERE id=%s"
cur.execute(sql, (id,))

Using this syntax, the arguments are escaped (these arguments are passed in parameters to the mogrify method https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/cursors.py#L161 and then _escape_args https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/cursors.py#L109)


Gist: https://gist.github.com/romainnorberg/2bc3d86237ee81b79639a33ff73d5b06

Doc/Related

  • Escape string Python for MySQL (StackOverflow): https://stackoverflow.com/a/27575399/3693616
  • Mogrify: https://www.compose.com/articles/formatted-sql-in-python-with-psycopgs-mogrify/
Romain Norberg

Romain Norberg

Php developer, play with Symfony and PhalconPhp frameworks.
More on LinkedIn or Github