DEV Community

Romain Norberg
Romain Norberg

Posted on

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

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 (1)

Collapse
sara123f profile image
kimberly123

hi can you help me i dont understand what does this do in your code: print("%d result ✋" % len(result)).

and if someone typ in , in drop table what will happen then
and what does cursor.excute do sorry for asking so much but really want to understand it