以前にもありましたが、MySQLでの日本語の文字化け
データをインサートして内容を表示すると以下のような状態。
mysql> select * from temperature_new;
+———-+——-+———+——+——+——————+
|DATE | KOSUI | AVERAGE | HIGH | LOW | TENKI
| +———-+——-+———+——+——+——————+
| 20130301 | 16.5 | 13.6 | 17.6 | 7.9 | ? |
| 20130302 | 0.0 | 8.7 | 12.0 | 4.8 | ? |
| 20130303 | 0.0 | 6.8 | 9.7 | 3.7 | ???? |
| 20130304 | 0.5 | 6.4 | 9.4 | 4.2 | ????? |
DB全体ではCharsetをUTF8に設定していましたが、実はCharsetはdatabaseごとの設定値で、databaseが作成された時点でcharsetは決定されます。このdatabase毎のcharsetはalterコマンドで変更が可能ですが、さらにその設定はテーブル作成時のdatabaseの設定によってテーブルごとの設定値となるようです。そして、テーブルごとのcharsetの設定値は変更も不可能の模様。
今回は以下のようにdatabaseのcharsetを変更後、さらにテーブルを再度作成して問題を解消できました。
mysql> show variables like ‘char%’;
+————————–+—————————-+
| Variable_name | Value |
+————————–+—————————-+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| 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)
mysql> alter database weather character set utf8
-> ; Query OK, 1 row affected (0.02 sec)
mysql> show variables like ‘char%’;
+————————–+—————————-+
| 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)
character_set_databaseはデータベース毎の設定で、connectしているdatabase毎に異なる値を示す可能性があります。