zoukankan      html  css  js  c++  java
  • Python SQL execute加参数的原理

    在Python中,当用pymysql库,或者MySQLdb库进行数据库查询时,为了防止sql注入,可以在execute的时候,把参数单独带进去,例如:

    def execute_v1():
        config = {
            'user': 'root',
            'password': 'password1',
            'host': '127.0.0.1',
            'database': 'selfmoe',
            'port': 3307,
            'charset': 'utf8'
        }
    
        import pymysql  # 打开数据库连接
        cnx = pymysql.connect(**config)
        cur = cnx.cursor()
        cur.execute('select title,id from post where title =%(title)s', dict(title="**'*"))
        ret = cur.fetchall()
        print ret
        cur.close()
        cnx.close()
        return ret
    
    
    execute_v1()
    

    cur.execute('select title,id from post where title =%(title)s', dict(title="**'*"))这行中,title这个参数是以args的形式传进去的
    查看pymysql的源码发现,当有args参数时,pymysql会做以下逻辑:

    • 如果是入参是unicode,encode为utf8
    • 如果是字符串,在两边加单引号
    • 使用escape_string(from pymysql import escape_string)函数对字符串进行转义
    • 然后通过%来拼合字符串,得到最终的sql

    所以

    • 使用args参数,其实和自己手动转义的效果是一样的,最终传给mysql的也是只有一个sql字符串。不过使用args可以把转义部分交给pymysql,这样安全性,稳定性更好,避免自己漏了转义,避免自己处理转义的异常情况。
  • 相关阅读:
    如何搜索 git 提交记录
    使用Mongo进行分页
    mongodb 数据自动备份
    linux 添加环境变量
    centos7安装bbr
    centos7安装node
    [shell]输出内容到剪切板
    centos 7 已经开启 22 端口但无法连接
    一些有趣的 js 包
    机房选择
  • 原文地址:https://www.cnblogs.com/Xjng/p/14647404.html
Copyright © 2011-2022 走看看