loading...

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

romainnorberg profile image Romain Norberg ・1 min read

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:

Doc/Related

Discussion

markdown guide