Django 中防止 SQL 注入的方法
方案一
总是使用 Django 自带的数据库 API. 它会根据你所使用的数据库服务器 (例如 PostSQL 或者 MySQL) 的转换规则, 自动转义特殊的 SQL 参数. 这被运用到了整个 Django 的数据库 API 中, 只有一些例外:
传给 extra() 方法的 where 参数. 这个参数故意设计成可以接受原始的 SQL. 使用底层数据库 API 的查询.
- ## select 提供简单数据
- # SELECT age, (age> 18) as is_adult FROM myapp_person;
- Person.objects.all().extra(select={
- 'is_adult': "age> 18"
- }) # 加在 select 后面
- ## where 提供查询条件
- # SELECT * FROM myapp_person WHERE first||last ILIKE 'jeffrey%';
- Person.objects.all().extra(where=["first||last ILIKE'jeffrey%'"]) # 加一个 where 条件
- ## table 连接其它表
- # SELECT * FROM myapp_book, myapp_person WHERE last = author_last
- Book.objects.all().extra(table=['myapp_person'], where=['last = author_last']) # 加 from 后面
- ## params 添参数
- # !! 错误的方式 !!
- first_name = 'Joe' # 如果 first_name 中有 SQL 特定字符就会出现漏洞
- Person.objects.all().extra(where=["first ='%s'" % first_name])
- # 正确方式
- Person.objects.all().extra(where=["first ='%s'"], params=[first_name])
python 中 sql 中注入
- from pymysql import *
- def main():
- find_name = input("请输入物品名称:")
- # 创建 Connection 连接
- conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
- # 获得 Cursor 对象
- cs1 = conn.cursor()
- # # 非安全的方式
- # # 输入 "or 1=1 or" (双引号也要输入)
- # sql = 'select * from goods where name="%s"' % find_name
- # print("""sql===>%s<====""" % sql)
- # # 执行 select 语句, 并返回受影响的行数: 查询所有数据
- # count = cs1.execute(sql)
- # 安全的方式
- # 构造参数列表
- params = [find_name]
- # 执行 select 语句, 并返回受影响的行数: 查询所有数据
- count = cs1.execute('select * from goods where name=%s', params)
- # 注意:
- # 如果要是有多个参数, 需要进行参数化
- # 那么 params = [数值 1, 数值 2....], 此时 sql 语句中有多个 %s 即可
- # 打印受影响的行数
- print(count)
- # 获取查询的结果
- # result = cs1.fetchone()
- result = cs1.fetchall()
- # 打印查询的结果
- print(result)
- # 关闭 Cursor 对象
- cs1.close()
- # 关闭 Connection 对象
- conn.close()
- if __name__ == '__main__':
- main()
请注意在 cursor.execute() 的 SQL 语句中使用 "%s", 而不要在 SQL 内直接添加参数. 如果你使用这项技术, 数据库基础库将会自动添加引号, 同时在必要的情况下转意你的参数.
来源: http://www.bubuko.com/infodetail-3344701.html