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')

原文地址:https://www.cnblogs.com/shiguanggege/p/14035870.html