MySQL在 5.5.3 之后增加了 utf8mb4 字符编码,mb4即 most bytes 4。简单说 utf8mb4 是 utf8 的超集并完全兼容utf8,能够用四个字节存储更多的字符。
有时,我们需要在mysql中存放emoji表情,emoji表情是1个字符占4个字节,而utf8编码只支持1-3个字节的字符,所以utf8编码下,如果直接存储表情,数据库存储会失败,所以需要改成utf8mb4。
需要修改:库、表、字段
修改数据库字符集:
ALTER DATABASE db_name DEFAULT CHARACTER SET character_name [COLLATE ...];如:ALTER DATABASE test DEFAULT CHARACTER SET utf8mb4; |
---|
把表默认的字符集和所有字符列改为新的字符集:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET character_name [COLLATE ...]如:ALTER TABLE logtest CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8_general_ci; |
---|
只是修改表的默认字符集:
ALTER TABLE tbl_name DEFAULT CHARACTER SET character_name [COLLATE...];如:ALTER TABLE logtest DEFAULT CHARACTER SET utf8mb4 COLLATE utf8_general_ci; |
---|
修改字段的字符集:
ALTER TABLE tbl_name CHANGE c_name c_name CHARACTER SET character_name [COLLATE ...];如:ALTER TABLE logtest CHANGE title title VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci; |
---|
查看数据库编码:
SHOW CREATE DATABASE db_name; |
---|
查看表编码:
SHOW CREATE TABLE tbl_name; |
---|
查看字段编码:
SHOW FULL COLUMNS FROM tbl_name; |
---|
查看当前数据库编码:
代码语言:javascript复制SHOW VARIABLES LIKE 'character_set_%';
mysql-connector-java驱动包在5.1.13 才支持utf8mb4
代码语言:javascript复制set global character_set_server=utf8mb4;
set global character_set_database=utf8mb4;
set global character_set_client=utf8mb4;
set global character_set_connection=utf8mb4;
修改配置文件:
代码语言:javascript复制修改mysql的my.cnf文件中的字符集
如:default-character-set = utf8mb4
character_set_server = utf8mb4
character-set-client-handshake = FALSE
collation-server = utf8mb4_unicode_ci
init_connect='SET NAMES utf8mb4'
重启mysql:
有些情况下修改后并不及时生效,需要重启mysql