Mysql失败,异常 InternalError: (1366, u"Incorrect string value: '\\xF0\\x9F\\x90\\

插入Mysql时失败了,python代码报如下异常:
    InternalError: (1366, u"Incorrect string value: '\\xF0\\x9F\\x90\\x98\\xE8\\ ......

解析:UTF-8编码有可能是两个、三个、四个字节。Emoji表情是4个字节,而Mysql的utf8编码最多3个字节,所以数据插不       进去。解决方案就是:将Mysql的编码从utf8转换成utf8mb4。网上应该能搜到一大堆修改Mysql编码的方法。

1、将已经建好的表也转换成utf8mb4
     命令:alter table TABLE_NAME convert to character set utf8mb4 collate utf8mb4_bin; (将TABLE_NAME替换成你的表名)

2、数据库链接
   conn=pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        passwd='123456',
        db='db1',
        charset='utf8mb4',
        )
3. 创建表

cursor.execute("create table TABLE_NAME (城市信息 text,自然科学 text)character set utf8mb4;")

猜你喜欢

转载自blog.csdn.net/zhenzi_PeppaPig/article/details/88890174