将pyodbc.Binary数据(BLOB)插入SQL Server映像列

sla*_*man 4 python pyodbc sql-server-2008

我试图将二进制数据插入imageSQL Server数据库中的数据类型列.我知道varbinary(max)是首选的数据类型,但我无权更改架构.

无论如何,我正在读取文件的内容并将其包装在pyodbc.Binary()中,如下所示:

f = open('Test.ics', 'rb')
ablob = f.read().encode('hex')
ablob = pyodbc.Binary(ablob)
Run Code Online (Sandbox Code Playgroud)

当我print repr(ablob)看到正确的值bytearray(b'424547494e3a5 . . .(省略号添加).

但是,插入后

insertSQL = """insert into documents(name, documentType, document, customerNumber) values(?,?,?,?)"""
cur.execute(insertSQL, 'test200.ics', 'text/calendar', pyodbc.Binary(ablob), 1717)
Run Code Online (Sandbox Code Playgroud)

文档列的值0x343234353 . . .看起来好像十六进制数据已转换为ASCII字符代码.

我想在pyodbc.Binary()中包装值会解决这个问题吗?任何帮助将不胜感激.

我使用的是Python 2.7和SQL Server 2008 R2(10.50).

编辑:

熊女士善意地指出,我不必要地调用编码('hex'),这导致了我的问题.我相信这一定是将数据强制转换为字符串(尽管更全面的解释会有所帮助).

工作代码:

ablob = pyodbc.Binary(f.read())
cur.execute(insertSQL, 'test200.ics', 'text/calendar', ablob, 1717)
Run Code Online (Sandbox Code Playgroud)

Bry*_*yan 5

首先确保您使用with open(..)读取文件(另一个例子).这会在文件对象耗尽引发异常时自动关闭它们.

# common vars
connection = pyodbc.connect(...)
filename = 'Test.ics'
insert = 'insert into documents (name, documentType, document, customerNumber)'

# without hex encode
with open(filename, 'rb'):
    bindata = f.read()

# with hex encode
with open(filename, 'rb'):
    hexdata = f.read().encode('hex')

# build parameters
binparams = ('test200.ics', 'text/calendar', pyodbc.Binary(bindata), 1717)
hexparams = ('test200.ics', 'text/calendar', pyodbc.Binary(hexdata), 1717)

# insert binary
connection.cursor().execute(insert, binparams)
connection.commit()

# insert hex
connection.cursor().execute(insert, hexparams)
connection.commit()

# print documents
rows = connection.cursor().execute('select * from documents').fetchall()
for row in rows:
    try:
        # this will decode hex data we inserted
        print str(row.document).decode('hex')
    # attempting to hex decode binary data throws TypeError
    except TypeError:
        print str(row.document)
Run Code Online (Sandbox Code Playgroud)

我猜测你是0x343234353...通过查看Management Studio中的结果来获取数据的:

SQL Server Management Studio结果

这并不意味着数据存储这种方式,它只是Management Studio中代表的方式image,text,ntext,varbinary,等数据类型在结果窗格中.