报错及原因分析
使用pymysql 插入包含特殊字符,例如表情字符的数据,报如下错误:
pymysql.err.InternalError: (1366, "Incorrect string value:
'\\xF0\\x9D\\x90\\xB8' for column ' title
原因是MySQL utf8不支持特殊字符,需要用utf8mb4编码。
UTF-8编码有可能是两个、三个、四个字节。Emoji表情是4个字节,而Mysql的utf8编码最多3个字节,所以数据插不进去。
解决
修改数据库表字段编码为utf8mb4
alter table TABLE_NAME convert to character set utf8mb4 collate utf8mb4_bin
注意:排序规则不是 utf8mb4_general_ci
,而是utf8mb4_bin
修改数据库链接方式为utf8mb4
conn = pymysql.connect(host='localhost', user='root', password='root', port=3306, db='db_test', charset='utf8mb4')