Django 使用 MySQL 中文報錯

默認的 SQLite 一般不會出現這個錯誤,不過一旦切換到了 MySQL 上之後,事情就發生了,表現爲存入數據的時候顯示:

Incorrect string value: '\x01\x9D\x8C\x86' for column 'column_name' at row 1

很顯然 MySQL 自帶的編碼比較雞掰,使用了 latin1,但是我們要 utfmb4!

所以加入以下內容到 /etc/my.cnf 的最後並重啓 MySQL 服務器即可:

[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

確認一波是否真的修改好了:

MariaDB [(none)]> show variables like 'character%';
+--------------------------+------------------------------+
| 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                         |
| character_sets_dir       | /usr/share/mariadb/charsets/ |
+--------------------------+------------------------------+
8 rows in set (0.016 sec)

Shame on you, MySQL!