简体   繁体   English

无法使用python将来自mssql的二进制数据插入sqlite3

[英]Unable to insert binary data from mssql into sqlite3 using python

I am trying to query an Microsoft SQL 2005 database, process the data and write the keys to the data I updated to an sqllite3 database store locally on my machine. 我正在尝试查询Microsoft SQL 2005数据库,处理数据并将密钥写入更新后的数据,这些数据已更新到本地计算机上的sqllite3数据库中。

The tools I'm using are python 2.7, pyodbc and sqllite3. 我使用的工具是python 2.7,pyodbc和sqllite3。 I am on windows 7 and the driver I've tried connecting to my mssql db using the sql server and sql native client driver with pyodbc and both yield the same results. 我在Windows 7上,并且我尝试使用带pyodbc的sql服务器和sql native客户端驱动程序连接到我的mssql db的驱动程序,并且都产生相同的结果。

The field I am having issues with is a uuid field that is binary(16) in mssql. 我遇到的字段是mssql中的binary(16)的uuid字段。 When I query the data using pyodbc it is coming back to me in a bytearray(). 当我使用pyodbc查询数据时,它将以bytearray()的形式返回给我。

This is the output I get when I run the following. 这是我运行以下命令时得到的输出。

id = mycursor.fetchone()
print id

àO÷ eÅO‹1ÝWt'E àO÷ eÅO‹1ÝWt'E

repr(id)

bytearray(b'\\xe0O\\xf7\\x1d\\x9de\\xc5O\\x8b1\\x0e\\xddWt\\x91E') 字节数组(b'\\ xe0O \\ xf7 \\ x1d \\ x9de \\ xc5O \\ x8b1 \\ x0e \\ xddWt \\ x91E')

When I go to insert that Id into an sqllite3 database I get the following. 当我将该ID插入sqllite3数据库时,得到以下信息。

s = sqlite3.connect('tmp.db')
cursor = s.cursor()
s.execute("create table recs(uuid blob)")
s.commit()
s.execute("insert into recs (uuid) values(?)", id)

1 s.execute("insert into recs (uuid) values(?)", id) 1 s.execute(“插入记录(uuid)值(?)”,id

ProgrammingError: Incorrect number of bindings supplied. ProgrammingError:提供的绑定数不正确。 The current statement uses 1, and there are 16 supplied. 当前语句使用1,并且提供了16。

The Python value needs to be a buffer object: Python值必须是一个buffer对象:

>>> s.execute("insert into recs (uuid) values(?)", (buffer(id), ))
<sqlite3.Cursor object at 0x011CD2E0>
>>> r = s.execute("select * from recs").fetchone()
>>> r
(<read-write buffer ptr 0x011F9280, size 16 at 0x011F9260>,)
>>> r[0]
<read-write buffer ptr 0x011F9280, size 16 at 0x011F9260>
>>> str(r[0])
'\xe0O\xf7\x1d\x9de\xc5O\x8b1\x0e\xddWt\x91E'
>>> str(r[0]) == id
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM