Python如何向SQLServer存儲(chǔ)二進(jìn)制圖片
需求是需要用python往 SqlServer中的image類型字段中插入二進(jìn)制圖片
核心代碼,研究好幾個(gè)小時(shí)的代碼:
安裝pywin32,adodbapiimage_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()# 讀取圖片,二進(jìn)制格式,注意是rbf1 = open(local_filename, 'rb', )b = f1.read()f1.close()# adodbapi支持插入二進(jìn)制數(shù)據(jù)流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在數(shù)據(jù)表是主鍵docimageid = str(DocId) + str(image_location)print 'docimageid', docimageidsql6 = ' INSERT INTO docImages (DocId,docimageid,purpose) VALUES (%s,’%s’,’%s’) ' % (int(DocId), int(docimageid), ’doclogo’)# print sql6cursor.execute(sql6)conn.commit()#插入圖片cursor.execute(’update docImages set Img=? where docimageid= ? ’,(adodbapi.Binary(b), docimageid,))conn.commit()print '圖片保存成功'先插入相關(guān)信息,再去update圖片到數(shù)據(jù)庫(kù)里面。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. python中PyQuery庫(kù)用法分享3. python操作數(shù)據(jù)庫(kù)獲取結(jié)果之fetchone和fetchall的區(qū)別說明4. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)5. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效6. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總7. python 爬取嗶哩嗶哩up主信息和投稿視頻8. 關(guān)于HTML5的img標(biāo)簽9. ASP.NET MVC前臺(tái)動(dòng)態(tài)添加文本框并在后臺(tái)使用FormCollection接收值10. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能
