最近在MacOS下用django框架做web開發,於是用MacPorts安裝了MySQL5。但是測試時django的測試框架會報錯,原因是UTF8數據無法插入。
我們知道,MySQL安裝完成後默認編碼為latin1,並不適合中文應用。因此我們通常用下面的SQL語句創建數據庫:
CREATE DATABASE mydb DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;而django測試框架創建測試數據庫時並不會像這樣指定編碼,因此創建的數據庫編碼為latin1,導致加載UTF8數據時就會出錯。
貌似django並沒有提供創建數據庫時指定編碼的選項,因此只能修改MySQL服務器的默認編碼設置。下面以MacPorts下的mysql5為例說一下設置方法。
首先復制一份my.cnf到 /opt/local/etc/mysql5:
$ cd /opt/local/etc/mysql5/
$ sudo cp /opt/local/share/mysql5/mysql/my-small.cnf my.cnf
然後編輯my.cnf,在[mysqld]節添加以下兩行:
$ sudo vi my.cnf
[mysqld]
...
collation_server = utf8_general_ci
character_set_server = utf8保存退出後重啟mysqld:
$ sudo /opt/local/bin/mysqladmin5 -u root shutdown
$ sudo /opt/local/bin/mysqld_safe5 &這樣就可以了。確認一下:
mysql> show variables like collation_server;
+------------------+-----------------+
| Variable_name | Value |
+------------------+-----------------+
| collation_server | utf8_general_ci |
+------------------+-----------------+
1 row in set (0.00 sec)
mysql> show variables like character_set_server;
+----------------------+-------+
| Variable_name | Value |
+----------------------+-------+
| character_set_server | utf8 |
+----------------------+-------+
1 row in set (0.00 sec)
charlee