修改MySQL的默认编码设置

最近在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)

原文地址:
http://tech.idv2.com/2011/04/18/change-default-character-set-of-mysql/

This entry was posted in Technology and tagged , , . Bookmark the permalink. 2,064 views

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>