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,这样安全性,稳定性更好,避免自己漏了转义,避免自己处理转义的异常情况。
  • 相关阅读:
    2015.07.20MapReducer源码解析(笔记)
    Hive(笔记)
    HDFS入门(1)
    Zookepper(2015.08.16笔记)
    USB_ModeSwitch 介绍(转)
    Perl 模块 Getopt::Std 和 Getopt::Long
    在linux下设置开机自动启动程序的方法
    gcc Makefile 入门
    Linuxexec函数族及system函数
    signal(SIGHUP, SIG_IGN)的含义
  • 原文地址:https://www.cnblogs.com/Xjng/p/14647404.html
Copyright © 2011-2022 走看看