凉城旧巷
Python从入门到自闭,Java从自闭到放弃,数据库从删库到跑路,Linux从rm -rf到完犊子!!!

pymysql防sql注入

1、什么事SQL注入

因为传入的参数改变SQL的语义,变成了其他命令,从而操作了数据库。

产生原因:SQL语句使用了动态拼接的方式。

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"' % ('tom', 19)

cursor.execute(sql)


-- 假如 name = 'tom or 1=1'

-- 那么会被or短路为永远正确,会将所有 name=tom 的数据全部删除
delete from stu where name = 'tom' or 1=1 and age = 19

 

2、pymysql防注入

pymysql 的 execute 支持参数化 sql,通过占位符 %s 配合参数就可以实现 sql 注入问题的避免。

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))   # 参数为元组格式
  • execute的参数为元组格式
  • 不要因为参数是其他类型而换掉 %s,pymysql 的占位符并不是 python 的通用占位符
  • %s 两边不需要加引号,mysql 会自动去处理
posted on 2021-08-03 10:59  凉城旧巷  阅读(418)  评论(0编辑  收藏  举报