python SQLServer 存储图片

馋奶兔 提交于 2020-05-09 16:19:11

需求是需要用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图片到数据库里面。

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!