在zlib中编码并插入mysq

2024-04-20 02:38:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用户的输入,在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=值。解码... ),它不起作用。。你知道吗

错误代码示例:

'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,。。。 没有什么。你知道吗

有答案吗?你知道吗


Tags: iniddatavalueasciinotpositionrange
1条回答
网友
1楼 · 发布于 2024-04-20 02:38:24

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

我会这样做:

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

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

相关问题 更多 >