您的位置:首页 > 数据库 > MySQL

MySQLdb 防SQL注入,同时打印已执行的SQL

2015-08-01 14:57 615 查看
>>> 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 \\'\\' =\\'' "
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: