>>> import MySQLdb

>>> conn=MySQLdb.connect(user='root',passwd='root')

>>> cur=conn.cursor()

>>> sql = "select user from mysql.user where user='%s' and password = '%s' ";

>>> cur.execute(sql % ('aaa','aaa'))

0L

>>> cur.execute(sql % ("aaa","aaa' or '' ='"))  #SQL注入

3L

>>> cur._executed  #打印刚执行的SQL

"select user from mysql.user where user='aaa' and password = 'aaa' or '' ='' "  

>>> cur.fetchall()

(('root',), ('root',), ('root',))

>>> sql="select user from mysql.user where user=%s and password = %s "

>>> cur.execute(sql,("aaa","aaa' or '' ='"))  #SQL注入失败。将变量作为 execute 的参数传入,execute函数会自动进行转义,需要注意的是,所有的占位符都是%s, %s 两边不需要引号,execute会自动根据你传如参数的类型判断是否添加引号。

0L

>>> cur._executed

"select user from mysql.user where user='aaa' and password = 'aaa\\' or \\'\\' =\\'' "