MySQL 插入emoji表情字符
默认情况下,MySQL数据库不支持插入某些表情字符。类似报错 (Mysql2::Error: Incorrect string value: '\xF0\x9F\x91\x93'
# 在 mysql输入以下命令,确认 mysql server是否支持 utf8mb4 编码。
mysql> SHOW CHAR SET WHERE Charset LIKE "%utf8%";
+---------+---------------+--------------------+--------+
| Charset | Description | Default collation | Maxlen |
+---------+---------------+--------------------+--------+
| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |
| utf8mb4 | UTF-8 Unicode | utf8mb4_general_ci | 4 |
+---------+---------------+--------------------+--------+
# 建议更改数据库前,请做好备份!!!
# 备份现有数据库
mysqldump database_name -uyour_username -pyour_password > database_name.sql
# 还原至新数据库
mysql -h host -u user -p production_new < production_old.sql
# 选择数据库
mysql> use database_name;
# 选择更改的数据表 users
mysql> alter table users convert to character set utf8mb4 collate utf8mb4_general_ci;
# 选择需要修改的数据表字段
mysql> alter table users modify column nickname varchar(255) character set utf8mb4 collate utf8mb4_general_ci;
# 修改 rails里的 database.yml
# encoding: utf8 ==> encoding: utf8mb4 (此处有人说不用修改,但是不修改的话,确实依然报错)
default: &default
encoding: utf8mb4
重启MySQL服务器(是否重启不一定)
相关参考: http://mumaren.me/blog/2013/11/27/support-emoji-in-rails-3-dot-2-14/