因此,在将 JSON 对象放入我的 MySQL 数据库之前,我试图对其进行压缩(gzip 或类似格式)。我目前将数据存储为 BLOB。我尝试使用以下Java方法来压缩数据:
public static byte[] compress(String str) throws Exception {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return obj.toByteArray();
}
然后使用 setBytes()
和 PreparedStatement
将其存储在数据库中,我对此没有任何问题。我遇到的问题是在 Python 2.7 中解密数据我尝试使用 zlib.decompress()
无济于事。它似乎无法读取 Java 存储的数据。我还需要用 Python 编写一个转换脚本来将旧行压缩成这种新格式。因此,无论我需要 Python decompress()
可读的任何格式,无论它是用 Java 还是 Python 2.7 压缩的
我很乐意提供更多信息,以帮助找到解决我困境的方法。
谢谢。
编辑:一些 Python 代码:
class KitPvPMatch(Base):
""" The SQLAlchemy declarative model class for a User object. """
__tablename__ = 'kit_pvp_matches'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8'
}
match_id = Column(INTEGER(11), autoincrement=True, primary_key=True, nullable=False)
season = Column(Unicode(5), nullable=False)
winner = Column(Unicode(16), nullable=False)
loser = Column(Unicode(16), nullable=False)
ladder_id = Column(TINYINT(4), nullable=False)
data = Column(BLOB, nullable=False)
# The line in question
jsonData = json.loads(zlib.decompress(match.data))
# The error
error: Error -3 while decompressing data: incorrect header check
最佳答案
这是一篇关于 unzipping using zlib with a stream. 的帖子
否则,您是否尝试过 gzip.py 的 gzip 文档。您可能需要一个临时文件。 gzip is here. 的文档在以下关于 decompression. 的帖子中,针对这种方法有一个相当不错的解决方案.
如果您还没有,请确保您正在从 SQL 获取字节。 Python 很灵活,所以它可能是一个字符串。如果是这种情况,请在您的字符串上调用 bytearray(string)。
如果这不起作用:
- 您的 SQL 命令返回的数据是什么格式?
- 什么错误,如果有的话?
关于java - 在 Java 中压缩数据并在 Python 中解压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434289/