MySQL のデフォルト文字コードの設定
バイナリ版などでインストールを行った場合には、デフォルトの文字コードが latin1 の ままとなっている場合がある。DB で何かを始める前には、一旦デフォルト文字コードを確 認し、マルチバイト文字を扱うたの適切な文字コードに設定しておく。
実は latin1 の状態であっても、UTF-8 を正しく扱えているような場合もある。ただ、これ はどこかのタイミングで嵌ることになるので気をつけておいた方がよい。。
MySQL 文字コードの確認
MySQL の show variables コマンドで文字コード関連の変数を確認する。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
$ mysql -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 715 Server version: 5.0.45-Debian_1ubuntu3.3-log Debian etch distribution Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> show variables like 'character%'; +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | utf8 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | utf8 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ 8 rows in set (0.00 sec) |
上記の結果であれば UTF-8 に設定されており、問題無い。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
mysql> show variables like 'character%'; +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | latin1 | | character_set_connection | latin1 | | character_set_database | latin1 | | character_set_filesystem | binary | | character_set_results | latin1 | | character_set_server | latin1 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ 8 rows in set (0.00 sec) |
上記の場合には、デフォルト文字コードを変更しておく。
デフォルト文字コードの変更
/etc/my.cnf
MySQL の設定ファイルである上記のファイルの内容を変更しておく。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
[client] # 追加 default-character-set=utf8 # 追加 [mysql] # 追加 default-character-set=utf8 # 追加 [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Default to using old password format for compatibility with mysql 3.x # clients (those using the mysqlclient10 compatibility package). old_passwords=1 default-character-set=utf8 # 追加 character_set_server=utf8 # 追加 skip-character-set-client-handshake # 追加 [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid |
mysqld を再起動する。
# service mysqld restart |
再度 MySQL のコマンドで確認してみると、UTF-8 に変更されていることが確認できる。
なお、MySQL のバージョンは、v.5.0.45 になる。
1 comment
Comments
-
Hi, good post. I have been wondering about this topic,so thanks for posting. I’ll definitely be subscribing to your site.