将 MSSQL 图像/varbinary 列数据转换为文件

问题描述 投票:0回答:1

我有来自(未知)MSSQL 服务器的数据,位于

Image
类型的列中(我认为这是
varbinary
的旧变体)。

我想制作一个脚本(最好是 Python 或 Typescript,但可以对任何内容开放),它可以获取如下要点中的数据并输出文件。

我尝试了很多方法,但无法转换下面要点中的文件 - 转换后的文件已损坏。我想这是由于我自己的编码/转换技能缺陷造成的。

https://gist.github.com/tomfa/2f9e63ee1cc3cd012ac4c9b1031de39f

我的代码

下面是我尝试用Python解码数据。代码运行正常,但输出的 PDF 无效。

import binascii

s = open("data.dat").read()

# chop off the '0x' at the front.
s = s[2:]

# Decode hex to binary.
binary = binascii.unhexlify(s)

with open("test123.pdf", 'wb') as f:
    f.write(binary)
python sql-server varbinary
1个回答
0
投票

图像字段似乎被压缩了,需要解压缩数据才能读取。

from os import getenv
import pymssql
import zipfile

conn = pymssql.connect('server', 'user', 'password', 'database')
cursor = conn.cursor()
cursor.execute("""
SELECT %s, %s FROM %s;
""" % ('filename_column', 'image_column', 'table'))

def unzip(archive):
    with zipfile.ZipFile(archive, 'r') as zip:
        for file in zip.namelist():
            zip.extract(member=file)

row = cursor.fetchone()
while row:
    filename = row[1]
    imagedata = row[2]
    zip_path = f'./{filename}.zip'

    with open(zip_path, 'wb') as f:
        print("Writing %s" % filename)
        f.write(imagedata)

    unzip(zip_path)

    row = cursor.fetchone()

conn.close()

© www.soinside.com 2019 - 2024. All rights reserved.