在zlib中编码并插入到mysql中

时间:2015-11-18 08:51:10

标签: python mysql encoding utf-8

我有一个用户的输入,在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,... 什么都没有。

答案?

1 个答案:

答案 0 :(得分:1)

value.encode('zlib')的输出将是二进制的,不一定是有效的UTF-8(即几乎从不)。

我会这样做:

value = value.encode('zlib').encode('base64')

这将为您提供一个长ASCII字符串,可以安全地包含在您的SQL查询中。