【发布时间】:2016-07-16 03:46:36
【问题描述】:
更新:真正的问题是 MySQL utf8 不支持四字节 UTF-8 字符。
关于这个主题有几个问题,但似乎都不是我的问题,除了可能是this one,接受的答案对我不起作用。
我正在使用 MySQLdb 模块在 Python 中进行编码,并且我想将一些文本放入 MySQL 数据库中。数据库配置为 UTF-8,但文本偶尔包含 non-UTF-8 四字节 UTF-8 字符。
修改数据库的 Python 代码如下所示:
connection = MySQLdb.connect(
'localhost',
'root',
'',
'mydatabase',
charset='utf8',
use_unicode=True)
cursor = connection.cursor()
cursor.execute(
'update mytable set entryContent=%s where entryName=%s',
(entryContent, entryName))
connection.commit()
它目前会产生这个警告:
./myapp.py:233: Warning: Invalid utf8 character string: 'F09286'
(entry, word))
./myapp.py:233: Warning: Incorrect string value: '\xF0\x92\x86\xB7\xF0\x92...' for column 'entry' at row 1
(entryname, entrycontent))
当我使用mysql 命令行客户端查看实际进入数据库的内容时,我看到内容在第一次出现 non-UTF-8 四字节时被截断UTF-8 字符。
我不在乎保留 non-UTF-8 四字节 UTF-8 字符,所以我要做的就是替换所有 non-UTF-8 del> 四字节 UTF-8 字符和一些其他有效的 UTF-8 字符,所以我可以将文本放入数据库。
【问题讨论】:
-
entry.decode().encode('ascii', 'replace') -
@Peter Wood:
'Cognates include Hittite ???????????????? (lāman)'.decode().encode('ascii', 'replace')产生UnicodeDecodeError: 'ascii' codec can't decode byte 0xf0 in position 25: ordinal not in range(128) -
对不起,
'Cognates include Hittite ???????????????? (lāman)'.decode('utf-8').encode('ascii', 'replace'),给'Cognates include Hittite ???????? ?(l?man)'
标签: python mysql encoding utf-8