Django에서 유니 코드 문자열을 저장할 때 MySQL "잘못된 문자열 값"오류
first_name, last_name을 Django의 auth_user 모델에 저장하려고 할 때 이상한 오류 메시지가 나타납니다.
실패한 예
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
성공한 예
user.first_name = u'Marcin'
user.last_name = u'Król'
user.save()
>>> SUCCEED
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)
테이블 문자셋과 콜 레이션
auth_user 테이블에는 utf8_general_ci 데이터 정렬이 포함 된 utf-8 문자 세트가 있습니다.
UPDATE 명령의 결과
UPDATE 명령을 사용하여 위의 값을 auth_user 테이블로 업데이트 할 때 오류가 발생하지 않았습니다.
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
장고에서 데이터베이스 백엔드를 전환하면 위에 나열된 실패한 값을 PostgreSQL 테이블로 업데이트 할 수 있습니다. 이상하다.
mysql> SHOW CHARACTER SET;
+----------+-----------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+----------+-----------------------------+---------------------+--------+
...
| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |
...
그러나 http://www.postgresql.org/docs/8.1/interactive/multibyte.html 에서 다음을 발견했습니다.
Name Bytes/Char
UTF8 1-4
유니 코드 문자가 PostgreSQL에서는 최대 4 바이트이지만 MySQL에서는 3 바이트로 위의 오류가 발생 했습니까?
None of these answers solved the problem for me. The root cause being:
You cannot store 4-byte characters in MySQL with the utf-8 character set.
MySQL has a 3 byte limit on utf-8 characters (yes, it's wack, nicely summed up by a Django developer here)
To solve this you need to:
- Change your MySQL database, table and columns to use the utf8mb4 character set (only available from MySQL 5.5 onwards)
- Specify the charset in your Django settings file as below:
settings.py
DATABASES = {
'default': {
'ENGINE':'django.db.backends.mysql',
...
'OPTIONS': {'charset': 'utf8mb4'},
}
}
Note: When recreating your database you may run into the 'Specified key was too long' issue.
The most likely cause is a CharField
which has a max_length of 255 and some kind of index on it (e.g. unique). Because utf8mb4 uses 33% more space than utf-8 you'll need to make these fields 33% smaller.
In this case, change the max_length from 255 to 191.
Alternatively you can edit your MySQL configuration to remove this restriction but not without some django hackery
UPDATE: I just ran into this issue again and ended up switching to PostgreSQL because I was unable to reduce my VARCHAR
to 191 characters.
I had the same problem and resolved it by changing the character set of the column. Even though your database has a default character set of utf-8
I think it's possible for database columns to have a different character set in MySQL. Here's the SQL QUERY I used:
ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
If you have this problem here's a python script to change all the columns of your mysql database automatically.
#! /usr/bin/env python
import MySQLdb
host = "localhost"
passwd = "passwd"
user = "youruser"
dbname = "yourdbname"
db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname)
cursor = db.cursor()
cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)
sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
cursor.execute(sql)
db.close()
If it's a new project, I'd just drop the database, and create a new one with a proper charset:
CREATE DATABASE <dbname> CHARACTER SET utf8;
I just figured out one method to avoid above errors.
Save to database
user.first_name = u'Rytis'.encode('unicode_escape')
user.last_name = u'Slatkevičius'.encode('unicode_escape')
user.save()
>>> SUCCEED
print user.last_name
>>> Slatkevi\u010dius
print user.last_name.decode('unicode_escape')
>>> Slatkevičius
Is this the only method to save strings like that into a MySQL table and decode it before rendering to templates for display?
You can change the collation of your text field to UTF8_general_ci and the problem will be solved.
Notice, this cannot be done in Django.
You aren't trying to save unicode strings, you're trying to save bytestrings in the UTF-8 encoding. Make them actual unicode string literals:
user.last_name = u'Slatkevičius'
or (when you don't have string literals) decode them using the utf-8 encoding:
user.last_name = lastname.decode('utf-8')
Simply alter your table, no need to any thing. just run this query on database. ALTER TABLE table_name
CONVERT TO CHARACTER SET utf8
it will definately work.
'development' 카테고리의 다른 글
프로젝트가 여러 출처를 가질 수 있습니까? (0) | 2020.06.13 |
---|---|
스위프트 3 옵션 이스케이프 폐쇄 파라미터 (0) | 2020.06.13 |
Android : BOTTOM의 탭 (0) | 2020.06.13 |
액세스가 허용되지 않은 데이터베이스를 숨기는 방법 (0) | 2020.06.13 |
내용에 맞게 UITableView 크기 조정 (0) | 2020.06.13 |