我将md5哈希值存储为MSSQL数据库中的二进制(16)。我需要用pymssql插入几千个值,如果我用cursor.execute()
而不是cursor.executemany()
逐个插入值,这个值非常慢。
但问题是,我无法插入二进制数据,因为executemany接受我的md5哈希列表并将其视为字符串......
我的插入行看起来像这样:
# 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 :(得分: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)