zoukankan      html  css  js  c++  java
  • pymysql防sql注入

    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 会自动去处理
    博客内容仅供参考,部分参考他人优秀博文,仅供学习使用
  • 相关阅读:
    Python 文件操作
    Python 操作 sqlite
    Python中的random模块
    Linux系统下的/etc/nsswitch.conf文件
    Python 列表/元组/字典总结
    快斗之翼:python2的print和python3的print()
    田小计划:图解Python深拷贝和浅拷贝
    Python 自省指南
    Python运算符优先级
    tc: 模拟网络异常的工具
  • 原文地址:https://www.cnblogs.com/linagcheng/p/15093362.html
Copyright © 2011-2022 走看看