2014-01-16 45 views
1

我将MSD数据库中的md5哈希值存储为二进制文件(16)。我需要使用pymssql插入几千个值,如果我用cursor.execute()而不是cursor.executemany()逐个插入值,则该值非常慢。 但问题是,我不能插入二进制数据,因为executemany把我的MD5哈希值的列表,并把它作为一个字符串...用executemany插入二进制文件(16)

我插线看起来是这样的:

# generated from hashlib.md5('somestring').hexdigest() 
md5list = ['9e107d9d372bb6826bd81d3542a419d6', 'e4d909c290d0fb1ca068ffaddf22cbd0'] 
# query should look like this: insert into hashes (md5) values (0x9e107d9d372bb6826bd81d3542a419d6) 
cursor.executemany("insert into hashes (md5) values (0x%s)", md5list) 
# now we have a query like: insert into hashes (md5) values (0x'9e107d9d372bb6826bd81d3542a419d6') 

有一种用executemany插入哈希的方法?

回答

0

Cursor.executemany的查询参数应该是序列的序列。

使用`int(..,16)将十六进制字符串转换为int。

>>> int('9e107d9d372bb6826bd81d3542a419d6', 16) 
210103647840849757586127012022035159510L 
>>> hex(int('9e107d9d372bb6826bd81d3542a419d6', 16)) 
'0x9e107d9d372bb6826bd81d3542a419d6L' 

如何使用列表理解?

md5list = ['9e107d9d372bb6826bd81d3542a419d6', 
      'e4d909c290d0fb1ca068ffaddf22cbd0'] 
params = [[int(h, 16)] for h in md5list] 
cursor.executemany("insert into hashes (md5) values (%s)", params) 
+0

问题不是0x,但pymssql假定这是一个字符串类型,并将“”添加到它。当我尝试插入'0x ...'它根本不工作,因为mssql不想要一个字符串... – reox

+0

@reox,好的。我更新了答案。 – falsetru

+0

好吧,对不起,我编辑了你的答案,但那也是错误的......你不能在pymssql中使用%x,并且%s总是将它放入''中。 :(和字符串不工作与mssql – reox