小知识,大挑战!本文正在参与“ 程序员必备小知识 ”创作活动
坑1: Python操作mysql数据库出现pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax;
下面为python中做mysql数据库插入数据代码操作:
import pymysql.cursors
# 循环入库操作
for ll in range(0, len(wallPaperBeanList)):
# 连接MySQL数据库
connection = pymysql.connect(host='127.0.0.1', port=3306, user='ad', password='ad', db='AllThingArePower',
charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
# 通过cursor创建游标
cursor = connection.cursor()
insert_sql = "INSERT INTO 'wallpaper' ('category','view_img','img','created_time','img_tag') VALUES ("+ wallPaperBeanList[ll].category +','+wallPaperBeanList[ll].view_img +','+wallPaperBeanList[ll].img +','+wallPaperBeanList[ll].created_time +','+'null' +')'
# print('category==' + wallPaperBeanList[ll].category + ';view_img==' + str(
# wallPaperBeanList[ll].view_img) + ';img==' + str(wallPaperBeanList[ll].img) + ';created_time==' + str(wallPaperBeanList[ll].created_time) + ';img_tag==' + str(wallPaperBeanList[ll].img_tag))
cursor.execute(insert_sql)
# 提交SQL
connection.commit()
# 关闭数据连接
connection.close()
运行后就出现了下面这个异常,下面贴下完整的异常日志信息:
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 ''wallpaper' ('category','view_img','img','created_time','img_tag') VALUES (Origi' at line 1")1
正常文本没有问题 唯独html文本报错,刚开始我一直以为是mysql语法有错误,但找来找去始终没有找到可以改动的地方,百度后网上有博客讲mysql语句拼接的时候里面可能有参数有双引号导致的,使用pymysql.escape_string()方法把有双引号的参数处理一下就行,这个方案没有解决了我的问题,后来找到了一个比较好的解决方案,就是不要用%或者+操作符来拼接SQL语句,应该使用占位符。即execute的第二个参数。
修改后的代码:
import pymysql.cursors
# 循环入库操作
for ll in range(0, len(wallPaperBeanList)):
# 连接MySQL数据库
connection = pymysql.connect(host='127.0.0.1', port=3306, user='ad', password='ad', db='AllThingArePower',
charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
# 通过cursor创建游标
cursor = connection.cursor()
cursor.execute('insert into wallpaper (category,view_img,img,created_time,img_tag) values (%s,%s,%s,%s,%s)', (str(wallPaperBeanList[ll].category), str(
wallPaperBeanList[ll].view_img),str(wallPaperBeanList[ll].img),str(wallPaperBeanList[ll].created_time),str(wallPaperBeanList[ll].img_tag)))
# 提交SQL
connection.commit()
# 关闭数据连接
坑2: 写入数据库中途出现: Mysql失败,异常pymysql.err.InternalError: (1366, "Incorrect string value: '\xF0\x9D\x90\xBF;......
问题描述:
插入Mysql时失败了,python代码报如下异常:
pymysql.err.InternalError: (1366, "Incorrect string value: '\xF0\x9D\x90\xBF;......
原因分析:
UTF-8编码有可能是两个、三个、四个字节。Emoji表情是4个字节,而Mysql的utf8编码最多3个字节,所以数据插不进去。
解决方案:
修改Mysql表的字符集和Pymysql连接库时的字符集。
1、修改Mysql表的字符集
说明:将已经建好的表字符集转改成 utf8mb4,排序规则改为 utf8mb4_bin
命令:alter table TABLE_NAME convert to character set utf8mb4 collate utf8mb4_bin; (将TABLE_NAME替换成你的表名)
注意:排序规则不是 utf8mb4_general_ci,而是utf8mb4_bin,不要想当然
2、修改数据库连接的字符集
conn = pymysql.connect(host='localhost', user='root', password='root', port=3306, db='cncb', charset='utf8mb4')