python向mysql数据库插入数据时经常会碰到一些特殊字符,如单引号,双引号。
原代码
sql2 = "select ds, country, per_hundred from covid_vaccination_doses_per where country = '{}'".format(i[0])
报错
pymysql.err.ProgrammingError: (1064, “You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘Ivoire’’ at line 1”)
打印sql语句
select ds, country, per_hundred from covid_vaccination_doses_per where country = ‘Cote d’Ivoire’
字符串含有单引号或者双引号导致出错
解决方案:
- 自己加个反斜杠
sql2 = "select ds, country, per_hundred from covid_vaccination_doses_per where country = %s" % ("\""+i[0]+"\"")
- 使用replace方法将单引号和双引号前面加上反斜杠。
appid=appid.replace("’","\’") 将单引号转成\单引号
appid=appid.replace(’"’,’\"’) 将双引号转成\双引号
- execute()
cursor.execute(u’’‘update table set name = %s where id = %s;’’’ , (name.decode(‘utf-8’),index))
举例:
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