使用sqlalchemy将值插入VARBINARY列

时间:2015-05-27 07:03:17

标签: sql-server sqlalchemy

我正在使用MS SQL数据库,以及Python和sqlalchemy。一个表的列定义为

CREATE TABLE MyTable (
    ...
    [address] [varbinary] (16) NULL
    ...

表类MyTable是通过表反射生成的。 在我的Python代码中将字符串值分配给MyTable.address会触发异常

sqlalchemy.exc.StatementError: (builtins.TypeError) string argument without an encoding

将其写入数据库时​​。传递bytearray会产生数据库错误

(pymssql.OperationalError) (257, 
b'Implicit conversion from data type varchar to varbinary is not allowed. 
Use the CONVERT function to run this query.DB-Lib error message 20018, severity 16 [...]

我知道在二进制列中存储字符串需要编码,但我该如何提供该编码?我怎样才能使用sqlalchemy的ORM功能将二进制数据写入数据库?

因为我是通过反射创建我的表类,所以我不能像Insert binary file into MSSQL db (varbinary) with python pymssql

的答案中所描述的那样直接修改SQL代码

阅读sqlalchemy documentation on MS SQL也没有解决方案。

2 个答案:

答案 0 :(得分:1)

在将数据保存到数据库之前,首先尝试将数据转换为varbinary,因为地址字段的数据类型是varbinary。

select convert(varbinary,[the string or data to be convert])

答案 1 :(得分:1)

假设在我的情况下,address是一个大整数,可以写

a = 72037797995605455
MyTable.address = a.to_bytes(16, 'big')

This link(不幸的是,似乎已经死了)给了我关键的暗示。

相关问题