使用 Python 从 SQLite 解压缩 BLOB
Decompressing a BLOB from SQLite with Python
使用 Python 2.7,我将 SQLite 中的网页存储到 BLOB 类型的列中:
使用 zlib 进行压缩,我将其作为 sqlite3.Binary 类型插入。
没有压缩这工作正常:
db_body = sqlite3.Binary(page_body)
dbc.execute("insert into table (content) values ?", db_body)
压缩也可以正常工作:
db_body = sqlite3.Binary(zlib.compress(page_body))
dbc.execute("insert into table (content) values ?", db_body)
当我尝试检索压缩数据时出现问题。我尝试了以下方法:
dbc.execute("select content from table limit 1")
sql_result = dbc.fetchone()
page_content = zlib.decompress(sql_result[0])
但是结果 (page_content
) 是一个仍然被压缩的 str 类型。没有错误或异常。 sql_result[0]
的内容类型是 Buffer,因此解压缩函数正在更改数据类型而不是内容。
如果我同时压缩和重新压缩,而不是通过 sqlite,输出是好的:
db_body = sqlite3.Binary(zlib.compress(page_body))
page_content = zlib.decompress(db_body)
那么,如何解压缩我插入的数据,然后从 SQLite 检索数据?
您确定要使用 sqlite3.Binary
吗?
db = sqlite3.connect('/tmp/mydb')
db.execute('CREATE TABLE tbl (bin_clmn BLOB)')
db.execute('INSERT INTO tbl VALUES(?)', [buffer(zlib.compress(page_body))])
db.commit()
db.close()
db = sqlite3.connect('/tmp/mydb')
row = db.execute('SELECT * FROM tbl').fetchone()
page_body_decompressed = zlib.decompress(str(row[0]))
print page_body == page_body_decompressed
使用 Python 2.7,我将 SQLite 中的网页存储到 BLOB 类型的列中:
使用 zlib 进行压缩,我将其作为 sqlite3.Binary 类型插入。
没有压缩这工作正常:
db_body = sqlite3.Binary(page_body)
dbc.execute("insert into table (content) values ?", db_body)
压缩也可以正常工作:
db_body = sqlite3.Binary(zlib.compress(page_body))
dbc.execute("insert into table (content) values ?", db_body)
当我尝试检索压缩数据时出现问题。我尝试了以下方法:
dbc.execute("select content from table limit 1")
sql_result = dbc.fetchone()
page_content = zlib.decompress(sql_result[0])
但是结果 (page_content
) 是一个仍然被压缩的 str 类型。没有错误或异常。 sql_result[0]
的内容类型是 Buffer,因此解压缩函数正在更改数据类型而不是内容。
如果我同时压缩和重新压缩,而不是通过 sqlite,输出是好的:
db_body = sqlite3.Binary(zlib.compress(page_body))
page_content = zlib.decompress(db_body)
那么,如何解压缩我插入的数据,然后从 SQLite 检索数据?
您确定要使用 sqlite3.Binary
吗?
db = sqlite3.connect('/tmp/mydb')
db.execute('CREATE TABLE tbl (bin_clmn BLOB)')
db.execute('INSERT INTO tbl VALUES(?)', [buffer(zlib.compress(page_body))])
db.commit()
db.close()
db = sqlite3.connect('/tmp/mydb')
row = db.execute('SELECT * FROM tbl').fetchone()
page_body_decompressed = zlib.decompress(str(row[0]))
print page_body == page_body_decompressed