python向mysql插入特殊字符

向mysql数据库插入数据时经常会碰到一些特殊字符,如单引号,双引号。

cur.execute(u'''update table set name = %s where id = %s;''' , (p.decode('utf-8'),index))

name = "\\"; 
name2 = "\""
注意: cursor.execute()可以接受一个参数,也可以接受两个参数:
(1) cursor.execute("insert into resource(cid,name) values(%s, %s)" , (12,name) );
    这种格式是接受两个参数,MySQLdb会自动替你对字符串进行转义和加引号,不必再自己进行转义,执行完     此语句之后,resource表中多了一条记录: 12   \
(2) cursor.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   \




版权声明:本文为shellshine原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。