python之myslq操作

经典微博:https://blog.csdn.net/Zhihua_W/article/details/54313258

女神:https://www.cnblogs.com/Eva-J/p/5133716.html

菜鸟:http://www.runoob.com/python/python-mysql.html

举例:
name="I'mHere"
注意: 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

猜你喜欢

转载自www.cnblogs.com/sunxiuwen/p/9248221.html
今日推荐