python中怎么向mysql中存储图片
这篇文章给大家介绍python中怎么向mysql中存储图片,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
示例代码如下:
#!/usr/bin/python#-*-coding:utf-8-*-importMySQLdbasmdbimportsystry:fin=open("chrome.png")img=fin.read()fin.close()exceptIOError,e:print"Error%d:%s"%(e.args[0],e.args[1])sys.exit(1)try:conn=mdb.connect(host='localhost',user='testuser',passwd='test623',db='testdb')cursor=conn.cursor()cursor.execute("INSERTINTOImagesSETData='%s'"%\mdb.escape_string(img))conn.commit()cursor.close()conn.close()exceptmdb.Error,e:print"Error%d:%s"%(e.args[0],e.args[1])sys.exit(1)
首先,我们打开一个图片,并读取图片数据,代码如下:
fin=open("chrome.png")
img=fin.read()
接着,我们把图片数据插入到数据库中,并使用escape_string进行特殊字符串转义。代码如下:
cursor.execute("INSERTINTOImagesSETData='%s'"%\
mdb.escape_string(img))
(十三)读取图片
上一节中,我们把图片存储到数据库中了,在本节,我们将取回并保存为图片文件。本节示例如下:
#!/usr/bin/python#-*-coding:utf-8-*-importMySQLdbasmdbimportsystry:conn=mdb.connect(host='localhost',user='testuser',passwd='test623',db='testdb')cursor=conn.cursor()cursor.execute("SELECTDataFROMImagesLIMIT1")fout=open('image.png','wb')fout.write(cursor.fetchone()[0])fout.close()cursor.close()conn.close()exceptIOError,e:print"Error%d:%s"%(e.args[0],e.args[1])sys.exit(1)
首先,我们从数据库中读取一张图片数据:
cursor.execute("SELECTDataFROMImagesLIMIT1")
接着,我们以二进制的写方式打开一个文件,写入图片数据:
fout=open('image.png','wb')
fout.write(cursor.fetchone()[0])
关于python中怎么向mysql中存储图片就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。