需求是需要用python往 SqlServer中的image类型字段中插入二进制图片
核心代码,研究好几个小时的代码:
安装pywin32,adodbapi
安装pywin32,adodbapi
image_url = "图片链接"
try:
image_result = session.get(url=image_url, headers=headers, stream=True)
except:
image_result = session.get(url=image_url, headers=headers, stream=True)
local_filename = md5(image_url) + ".png"
print "图片下载成功"
with open(local_filename, 'wb') as f:
for chunk in image_result.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
f.close()
# 读取图片,二进制格式,注意是rb
f1 = open(local_filename, "rb", )
b = f1.read()
f1.close()
# adodbapi支持插入二进制数据流
Cfg = {'server': 'XXXXXXX9', 'password': 'XXXXXXX', 'db': 'XXXXXXX'}
constr = "Provider=SQLOLEDB.1; Initial Catalog=%s; Data Source=%s; user ID=%s; Password=%s; " % (Cfg['db'], Cfg['server'], 'drc_sql', Cfg['password'])
conn = adodbapi.connect(constr)
cursor = conn.cursor()
print "DocId", DocId
# docimageid在数据表是主键
docimageid = str(DocId) + str(image_location)
print "docimageid", docimageid
sql6 = " INSERT INTO docImages (DocId,docimageid,purpose) VALUES (%s,'%s','%s') " % (int(DocId), int(docimageid), 'doclogo')
# print sql6
cursor.execute(sql6)
conn.commit()
#插入图片
cursor.execute('update docImages set Img=? where docimageid= ? ',(adodbapi.Binary(b), docimageid,))
conn.commit()
print "图片保存成功"
先插入相关信息,再去update图片到数据库里面。
来源:oschina
链接:https://my.oschina.net/u/4332589/blog/4272093