python执行execute对mysql插入数据时的参数问题

[python] 2024-05-14 圈点564

摘要:python执行cursor.execute时的参数问题

cursor.execute()可以接受一个参数,也可以接受两个参数:


(1) cur.execute("insert into resource(cid,name) values(%s, %s)" , (12,name) );

连接符号是逗号:

    这种格式是接受两个参数,MySQLdb会自动替你对字符串进行转义和加引号,不必再自己进行转义,执行完此语句之后,resource表中多了一条记录: 12  I'mHere


(2) cur.execute("insert into resource(cid,name) values(%s, %s)" % (12,name) );

连接符号是百分号:

    这种格式是利用python的字符串格式化自己生成一个query,也就是传给execute一个参数,此时必须自己对字符串转义和增加引号,即上边的语句是错误的,应该修改为:

    name = MySQLdb.escape_string(name);
    cursor.execute("insert into resource(cid,name) values(%s, '%s')" % (12,name) );
    这样插入的记录才和(1)一样:12 I'mHere



  

相关内容:

感谢反馈,已提交成功,审核后即会显示