要讓 MySQL 開啓 utf8mb4 支持,須要一些額外的設置。python
1. 檢查 MySQL Server 版本mysql
2. 設置表的 CHARSETsql
建立表的時候指定 CHARSET 爲 utf8mb4app
CREATE TABLE IF NOT EXISTS table_name ( ... ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_general_ci;
或者修改已存在的表 CHARSET 爲 utf8mb4spa
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
3. 修改 MySQL 配置文件code
修改 my.conf 的內容server
[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
4. 檢查是否生效ip
正常狀況下的結果應該以下所示:ci
mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%'; +--------------------------+--------------------+ | Variable_name | Value | +--------------------------+--------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8mb4 | | character_set_system | utf8 | | collation_connection | utf8mb4_unicode_ci | | collation_database | utf8mb4_unicode_ci | | collation_server | utf8mb4_unicode_ci | +--------------------------+--------------------+
5. 指定 MySQL 鏈接時的 charsetunicode
以 mysql-python 爲例:
MySQLdb.connect(
host=config.DB_HOST,
port=config.DB_PORT,
user=config.DB_USR,
passwd=config.DB_PSW,
db=config.DB_NAME,
use_unicode=True,
charset="utf8mb4")
[1] http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters
[2] https://mathiasbynens.be/notes/mysql-utf8mb4#utf8-to-utf8mb4