mysql storage nickname with emoji processing scheme

1. Background

Recently, I developed a WeChat public account. The system needs to store basic information such as the user's openId and nickname. However, many trendy, WeChat nicknames will choose to use various emoji expressions, so I am not careful. As an uncle, I did not consider this problem when designing the table structure, and there was a problem that it could not be stored.

2. Modify the my.cnf configuration file

1. Because the previous design uses utf-8 encoding, with a maximum of three bytes, and Emoji expressions are four bytes, so the data cannot be inserted.

2. Query database encoding format

show variables like '%char%'

mysql encoding 1.png

3. Modify the server mysql configuration file

#1.mysql安装路径
>which mysqld
#2.查看读取my.cnf文件顺序
>/usr/sbin/mysqld --verbose --help |grep -A 1 'Default options'
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf 
#3.进入/etc/my.cnf修改配置文件
>cd /etc
>vim my.cnf
#4.将如下配置加入my.cnf配置文件
[client]
default-character-set = utf8mb4
[mysql]
default-character-set = utf8mb4
[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
init_connect='SET NAMES utf8mb4'

4. Restart mysql

service mysqld stop
service mysqld start

3. Modify the library table structure

alter database 数据库名称 character set =utf8mb4 collate=utf8mb4_unicode_ci;

alter table 表名 convert to character set utf8mb4 collate utf8mb4_unicode_ci;

alter table 表名 CHANGE 字段名 字段名varchar(255) 
CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

4. Check the encoding again

show variables like '%char%'

mysql encoding 2.png

5. After the above is completed, you can insert a nickname with emoji

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324678863&siteId=291194637