LoginSignup
6
1

More than 5 years have passed since last update.

MySQLに4byte文字を格納するまで

Last updated at Posted at 2017-12-15

文字コードutfmb4の設定が各所になされていないMySQLに4byte文字をインサートしようとすると
エラーが吐かれず、それ以降の文字列が途切れるので注意が必要。

UTF-8で4byte判定される文字

JIS X 0213の第3・4水準漢字の一部

絵文字

http://www.unicode.org/charts/PDF/U1F300.pdf
http://www.unicode.org/charts/PDF/U1F600.pdf

中国漢字

http://www.fileformat.info/info/unicode/block/cjk_unified_ideographs_extension_b/utf8test.htm
http://www.unicode.org/charts/PDF/U4E00.pdf

各種設定

MySQLのデフォルト設定

utf8mb4が対応されているのはMySQL 5.5以降なので、確認する。

[root@localhost]# mysql -v
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 735
Server version: 5.6.34-79.1-log Percona Server (GPL), Release 79.1, Revision 1c589f9

my.cnf(MySQLの設定ファイル)で下記を設定する。

[mysqld]
character-set-server = utf8mb4
skip-character-set-client-handshake

[client]
default-character-set=utf8mb4

MySQLを再起動して設定を確認する。

mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';
+--------------------------+--------------------+
| Variable_name            | Value              |
+--------------------------+--------------------+
| character_set_client     | utf8mb4            |
| character_set_connection | utf8mb4            |
| character_set_database   | utf8mb4            |
| character_set_filesystem | binary             |
| character_set_results    | utf8mb4            |
| character_set_server     | utf8mb4            |
| character_set_system     | utf8               |
| collation_connection     | utf8mb4_general_ci |
| collation_database       | utf8mb4_general_ci |
| collation_server         | utf8mb4_general_ci |
+--------------------------+--------------------+
10 rows in set (0.00 sec)

格納したいデータベース、テーブルも4byte文字の受け入れ態勢を整える

Laravelの場合、下記にてset names $charsetcollate $collationをしている
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Connectors/MySqlConnector.php#L15

        'mysql' => [
            (略)
            'charset'   => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
       (略)
        ],

それぞれutf8mb4が含まれる設定をした後
Illuminate\Support\Facades\Schema::create
でテーブル作成をすればvarcharカラムの照合順序はutf8mb4になる

結果

格納できた。

キャプチャ1213.JPG

参考

UTF8の4byte文字まとめ

あとがき

ユーザーが絵文字を使うサービスは、DBのバージョンが問われるのである.

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1