问题描述:
通过python把数据同步至mysql数据库的过程中,报以下错误:“ (pymysql.err.DataError) (1366, 'Incorrect string value: '\xF0\x9F\x98\x9D",...' for column 'html' at row 1')”
通过网上资料查询,最终解决了问题。
原因分析:
报错1366,主要是处理emoji时,编码问题造成的,在mysql8里面,字符集默认就是utf8mb4,已经支持emoji,python3默认就是utf8,utf8mb4时utf8的超集,mb4是most bytes 4的意思,专门用来兼容四字节的unicode,处理emoji时需要字符集支持unicode,utf8mb4是没问题的,但是uft8不可以。
解决方案:
首先需要将python连接mysql的默认格式由utf8改为utf8mb4:
"mysql+pymysql://root:123456@localhost:3306/test?charset="utf8mb4"
conn = pymysql.connect(user='root', passwd='123456', database='test', host='localhost', port=3306, charset='utf8mb4')
此时仅修改python连接mysql的编码格式再运行程序仍然报错,所以接下来还需要修改目标表的字符集为utf8mb4:
alter table table_name convert to character set utf8mb4;
都修改完之后,再运行程序,问题解决。
参考连接:
python3.7 mysql8报错:(pymysql.err.DataError)(1366,“Incorrect string value:‘“\x..._雨昱的博客-CSDN博客