Insert binary file into MSSQL db (varbinary) with python pymssql

橙三吉。 提交于 2019-12-01 00:42:04

As @Arno Rinker pointed out, there was indeed a problem with the conversion from varchar to varbinary. However, I ended up doing more than that to completely solve my problem.

I'm posting my whole solution here, just in case...

with open(tmp_file, 'rb') as content_file:
    filecontent = content_file.read()
    filecontent_hex = '0x'.encode('ascii') + binascii.hexlify(filecontent)

    --> post the value of filecontent_hex to a stored procedure.

The stored procedure receives the value of filecontent_hex as varchar, then converts it to varbinary.

Getting binary data out of the MSSQL-DB I then do like this:

fout = open(filename, "w")
filecontent_unhex = binascii.unhexlify(filecontent)
fout.write(filecontent_unhex[2:])
fout.close()

where filename and filecontent are in the result of the querying stored procedure.

Conclusion: The binascii.hexlify() and binascii.unhexlify() where not necessary for the binary interaction with SQLite and MySQL. However, these steps appeared to be required for the interaction with a MSSQL-DB.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!