Migrate to MySQL 4.1 using unicode

使用MySQL有年头了,受限于MySQL支持的字符集与编码,我以前的应用都是使用gb2312/gbk. 从4.1开始,MySQL正式支持unicode,以下是我的迁移实践。

Scenario:
现有的数据库mydb构建在MySQL 4.0.20上,使用gb2312作为缺省字符集,需要将其迁移到MySQL 4.1.14且使用utf8作为其缺省字符集。
MySQL 4.0.20 安装在 /opt/mysql 下,使用3306端口
MySQL 4.1.14 安装在 /opt/mysql2 下,使用3326端口

Migration:

首先把目前使用gb2312的数据库mydb中的内容使用mysqldump导出:

# /opt/mysql/bin/mysqldump -uroot -hlocalhost -pthepasswd -P3306 mydb > /backup/mydb_20050905.sql

接着使用此数据文件来构建目标库mydb_new :

Step 1, 使用缺省字符集(utf8)连接MySQL Server,然后使用字符集gb2312来创建目标库mydb_new.
# /opt/mysql2/bin/mysql -uroot -hlocalhost -pthepasswd -P3326
mysql> create database mydb_new default character set gb2312 collate gb2312_chinese_ci;
mysql> quit

Step 2, 使用字符集gb2312连接MySQL Server,然后运行先前导出的sql数据文件.
# /opt/mysql2/bin/mysql -uroot -hlocalhost -pthepasswd -P3326 –default-character-set=gb2312
mysql> use mydb_new
mysql> source /backup/mydb_20050905.sql
mysql> quit

Step 3, 使用缺省字符集(utf8)连接MySQL Server,然后依次修改数据库mydb_new中的每个table的缺省字符集为utf8.
# /opt/mysql2/bin/mysql -uroot -hlocalhost -pthepasswd -P3326
mysql> use mydb_new
mysql> alter table table_xxx convert to character set utf8 collate utf8_general_ci;
mysql> quit

Step 4, 使用缺省字符集(utf8)连接MySQL Server,然后修改数据库mydb_new的缺省字符集为utf8.
# /opt/mysql2/bin/mysql -uroot -hlocalhost -pthepasswd -P3326
mysql> alter database mydb_new default character set utf8 collate utf8_general_ci;
mysql> quit

OK.

Updates:

不知为何,mysqldump很容易丢失数据,特别是长文章,莫名其妙地被截去了一些内容。后来我都是自己写程序从原先的库里读、再按ID对应更新到新的库里面去。我猜应该是由于特殊字符导致的。

This entry was posted in Uncategorized. Bookmark the permalink.

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=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">