在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

mysql存储emoji表情的时候,就会报错,如下:

Error updating database. Cause: java.sql.SQLException: Incorrect string value: ‘\xF0\x9F\x98\x8A\xF0\x9F…’ for column ‘这是我表中的字段’ at row 1

初步定位是我的数据库是utf8编码,不支持emoji表情,需要改成utf8mb4编码

具体原因:

emoji表情需要4个字节存储
mysql的utf8编码的一个字符最多3个字节,所以不够了就报错

解决如下
1.mysql将字符集 utf8改utf8mb4:

ALTER TABLE 你的表名 CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

2.修改数据源配置
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
	<property name="url" value="${mysql.url}" />
	<property name="username" value="${mysql.user}" />
	<property name="password" value="${mysql.password}" />
	<!-- 设置编码,支持表情存储-->
	<property name="connectionInitSqls" value="set names utf8mb4;"/>
</bean>

扩展:

1、mysql编码:utf8和utf8mb4的区别:

看官网文档:https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-sets.html

utf8mb4: A UTF-8 encoding of the Unicode character set using one to four bytes per character.
utf8mb4: Unicode字符集的UTF-8编码,每个字符使用1到4个字节。
utf8mb3: A UTF-8 encoding of the Unicode character set using one to three bytes per character.
utf8mb3: Unicode字符集的UTF-8编码,每个字符使用一到三个字节。
utf8: An alias for utf8mb3.
utf8: utf8mb3的别名。

UTF-8是使用1~4个字节,一种变长的编码格式。
MySQL中的utf8是utfmb3,只有三个字节,节省空间但不能表达全部的UTF-8,只能支持“基本多文种平面”(Basic Multilingual Plane,BMP)。

总结:编码一般都使用utf8mb4。

utf8扩展,除了mb3,mb4,还有以下:

ucs2: The UCS-2 encoding of the Unicode character set using two bytes per character.
ucs2: Unicode字符集的UCS-2编码,每个字符使用两个字节。
utf16: The UTF-16 encoding for the Unicode character set using two or four bytes per character. Like ucs2 but with an extension for supplementary characters.
utf16: Unicode字符集的UTF-16编码,每个字符使用两个或四个字节。就像ucs2一样,但是有一个补充字符的扩展。
utf16le: The UTF-16LE encoding for the Unicode character set. Like utf16 but little-endian rather than big-endian.
utf16le: Unicode字符集的UTF-16LE编码。类似于utf16,但是是little-endian(小端)而不是big-endian(大端)。
utf32: The UTF-32 encoding for the Unicode character set using four bytes per character.
utf32: Unicode字符集的UTF-32编码,每个字符使用四个字节。

2、mysql排序:utf8_bin和utf8_general_ci和utf8_unicode_ci的区别

ci是 case insensitive, 即 “大小写不敏感”, a 和 A 会在字符判断中会被当做成一样的;
bin 是二进制, a 和 A 会别区别对待.
utf8_unicode_ci校对规则仅部分支持Unicode校对规则算法,一些字符还是不能支持。
SELECT * FROM user WHERE name = 'a’查询时,
使用utf8_bin排序就找不到name = 'A’的那行
使用utf8_general_ci排序就能找到name = 'A’的那行

整理:utf8_bin区分大小写,utf8_unicode_ci比较准确,utf8_general_ci速度比较快。通常情况下 utf8_general_ci的准确性也够我们用的了

总结:排序一般都使用utf8_general_ci

Logo

更多推荐