Python连接MySQL数据库执行sql语句时的参数问题

由于工作需要,今天写了一个Python小脚本,其中需要连接MySQL数据库,在执行sql命令时需要传递参数,结果出问题了。在网上查了一下,发现有以下几种方式传递参数:

一.直接把sql查询语句完整写入字符串

try:
        connection = MySQLdb.connect(user="secsel",passwd="secsel@55",host="192.168.138.55",db="anbench")
    except:
        print "Could not connect to MySQL server."
        exit( 0 )

    cursor = connection.cursor()
    cursor.execute( "SELECT a.id,a.md5,CONCAT(b.`from_name`,'/',b.`suffix`,'/',a.`md5`) FROM apk_sec a,apk_from b WHERE a.`apk_from_id`=b.`id` AND a.md5 = %s", apk_md5)

  二.使用参数替代

city = 'beijing'

cur.execute(“SELECT * FROM %s WHERE city = %s”, city)

  

#注意此处的占位符统统是%s字符串类型,不再区分字符串,数字或者其他类型。另外%s不能加引号,如”%s”这是错误的写法。我就是加引号出错了。

变量替代的时候还有一种写法:

cur.execute(“SELECT * FROM %s WHERE city = %s” %city)

  

前面代码使用了逗号,这里使用了百分号%。两者区别在于变量的解释方式。使用逗号,变量是作为execute的参数传入的,由MySQLdb的内置方法把变量解释成合适的内容。使用百分号%则是用Python编译器对%s执行相应的替代,这种方法是有漏洞的,有些时候(比如包含某些特殊字符的时候)不能正常解析,甚至会有注入漏洞。一般情况下都要把变量作为execute的参数传入。

3.使用字典dict类型传递变量

sql = “INSERT INTO user VALUES(%(username)s, %(password)s, %(email)s)”

value = {“username”:zhangsan,

“password”:123456,

“email”:[email protected]}

cur.execute(sql, value)

  

上面这种方法适合字段比较多的时候,变量顺序不会错。

附上我写的脚本代码相关部分:

def get_apkpath(apk_md5):
    try:
        connection = MySQLdb.connect(user="***",passwd="***",host="192.168.***.***",db="***")
    except:
        print "Could not connect to MySQL server."
        exit( 0 )

    cursor = connection.cursor()
    cursor.execute( "SELECT a.id,a.md5,CONCAT(b.`from_name`,'/',b.`suffix`,'/',a.`md5`) FROM apk_sec a,apk_from b WHERE a.`apk_from_id`=b.`id` AND a.md5 = %s", apk_md5)  #注意不要加引号
    print "Rows selected:", cursor.rowcount

    for row in cursor.fetchall():
        print "note : ", row[0], row[1], row[2]        
    cursor.close()
    return row[2]

  

猜你喜欢

转载自www.cnblogs.com/qiaoxin/p/10006839.html