Django 使用 MySQL 中文報錯

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!