Django sql注入及解决方案
前言:sql注入多发生在拼接sql语句等场景,对数据库进行越权访问或其他危险操作,危害极其严重,本文介绍在django中sql注入的预防措施。
示例:
简单的查询语句:
my_connection = connections['default']
with my_connection.cursor() as cursor:
sql = "select * from my_table where id=%s "%(pk)
cursor.execute(sql)
result = cursor.fetchall()
当进行如图所示的查询操作时,将获取my_table数据表所有数据
解决方案:
一:使用django的orm查询,可有效避免sql注入问题。较简单,不在此赘述
二:参数化查询
1.简单查询,上述查询代码修改为:
my_connection = connections['default']
with my_connection.cursor() as cursor:
sql = '''select * from my_table where id = "%s" '''
cursor.execute(sql,[pk])
cursor.execute(sql)
result = cursor.fetchall()
sql注入问题得以避免
2.模糊查询,如含like的语句,将参数处理为 “%{}%”的格式:
my_connection = connections['default']
with my_connection.cursor() as cursor:
sql = '''select * from my_table where id like %s '''
cursor.execute(sql,['%{}%'.format(pk)])
cursor.execute(sql)
result = cursor.fetchall()