Saya mendapat pesan kesalahan aneh ketika mencoba menyimpan first_name, last_name ke model auth_user Django.
Contoh gagal
user = User.object.create_user(username, email, password)
user.first_name = u'Rytis'
user.last_name = u'Slatkevičius'
user.save()
>>> Incorrect string value: '\xC4\x8Dius' for column 'last_name' at row 104
user.first_name = u'Валерий'
user.last_name = u'Богданов'
user.save()
>>> Incorrect string value: '\xD0\x92\xD0\xB0\xD0\xBB...' for column 'first_name' at row 104
user.first_name = u'Krzysztof'
user.last_name = u'Szukiełojć'
user.save()
>>> Incorrect string value: '\xC5\x82oj\xC4\x87' for column 'last_name' at row 104
Contoh sukses
user.first_name = u'Marcin'
user.last_name = u'Król'
user.save()
>>> SUCCEED
Pengaturan MySQL
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)
Tabel charset dan collation
Tabel auth_user memiliki charset utf-8 dengan collation utf8_general_ci.
Hasil dari perintah UPDATE
Itu tidak menimbulkan kesalahan ketika memperbarui nilai-nilai di atas ke tabel auth_user dengan menggunakan perintah UPDATE.
mysql> update auth_user set last_name='Slatkevičiusa' where id=1;
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select last_name from auth_user where id=100;
+---------------+
| last_name |
+---------------+
| Slatkevi?iusa |
+---------------+
1 row in set (0.00 sec)
PostgreSQL
Nilai-nilai gagal yang tercantum di atas dapat diperbarui ke tabel PostgreSQL ketika saya mengganti database backend di Django. Ini aneh.
mysql> SHOW CHARACTER SET;
+----------+-----------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+----------+-----------------------------+---------------------+--------+
...
| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |
...
Tetapi dari http://www.postgresql.org/docs/8.1/interactive/multibyte.html , saya menemukan yang berikut:
Name Bytes/Char
UTF8 1-4
Apakah ini berarti unicode char memiliki maksimal 4 byte di PostgreSQL tetapi 3 byte di MySQL yang menyebabkan kesalahan di atas?