Django ORM

模型查询

使用Django自己提供的模型层语法进行数据查询可以防止SQL注入

1
asns = FpingAsn.objects.filter(operator_id__in=operators).values_list('asn', flat=True)

使用原生SQL

方式一:

1
2
3
4
5
from django.db import connection
cursor = connection.cursor()
query_sql = "select count(*) from automatic_product.subinterface where is_alloc = 1 and site_id = '{}' and app_id is not null and status = 'ok'".format(site.id)
cursor.execute(query_sql)
used_count = cursor.fetchall()
  • 这种方式下,不能防止SQL注入,需要把参数拆开查询

方式二:

1
2
3
id_str = "中国电信 or 1=1 --"
sql = "select * from fping_operator where name = %s"
fs = FpingOperator.objects.raw(sql, [id_str])
  • raw通过这种方式也可以防止sql注入,类似于execute,但是自己拼接sql字符串后调用raw不能防sql注入

pymysql

1
2
3
4
5
6
7
8
import pymysql

conn = pymysql.connect(host="xxx", port=3306, user="xxx", passwd="xxx", db="xxx")
cursor = conn.cursor()

sql = 'delete from stu where name = %s and age = %s'

cursor.execute(sql, ('tom', 19)) # 参数为元组格式
  • pymysql 的 execute 支持参数化 sql,通过占位符 %s 配合参数就可以实现 sql 注入问题的避免