我有一个用户的输入,在 utf8 中,很长。 我想通过压缩将其放入 mysql 中。 所以:
value = value.decode('utf8', 'replace')
value = value.encode('zlib')
cursor.execute('''INSERT INTO data (data_id, value) VALUES (%s,%s)''', (data_id, value , ))
无论我做什么 (value = str(value), value = value.decode...),它都不起作用..
错误代码示例:
'ascii' codec can't encode character u'\xe9' in position 8177: ordinal not in range(128)
'ascii' codec can't encode character u'\xe9' in position 747: ordinal not in range(128)'ascii' codec can't encode character u'\xe9' in position 2478: ordinal not in range(128)
我尝试更改字段的结构:longtext、longbinary、blob、... 什么都没有。
一个答案?
最佳答案
value.encode('zlib')
的输出将是二进制的,不一定是有效的 UTF-8(即几乎从不)。
我会这样做:
value = value.encode('zlib').encode('base64')
这将为您提供一个很长的 ASCII 字符串,可以将其安全地包含在您的 SQL 查询中。
关于python - 在 zlib 中编码并插入到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33775433/