這篇文章給大家介紹python中怎么向MySQL中存儲圖片,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
創(chuàng)新互聯(lián)是專業(yè)的二道江網(wǎng)站建設(shè)公司,二道江接單;提供網(wǎng)站設(shè)計、成都做網(wǎng)站,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行二道江網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
示例代碼如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
import systry:
fin = open("chrome.png")
img = fin.read()
fin.close()
except IOError, 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("INSERT INTO Images SET Data='%s'" % \
mdb.escape_string(img))
conn.commit()
cursor.close()
conn.close()
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
首先,我們打開一個圖片,并讀取圖片數(shù)據(jù),代碼如下:
fin = open("chrome.png")
img = fin.read()
接著,我們把圖片數(shù)據(jù)插入到數(shù)據(jù)庫中,并使用escape_string進行特殊字符串轉(zhuǎn)義。代碼如下:
cursor.execute("INSERT INTO Images SET Data='%s'" % \
mdb.escape_string(img))
(十三)讀取圖片
上一節(jié)中,我們把圖片存儲到數(shù)據(jù)庫中了,在本節(jié),我們將取回并保存為圖片文件。本節(jié)示例如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
import systry:
conn = mdb.connect(host='localhost',user='testuser',
passwd='test623', db='testdb')
cursor = conn.cursor()
cursor.execute("SELECT Data FROM Images LIMIT 1")
fout = open('image.png','wb')
fout.write(cursor.fetchone()[0])
fout.close()
cursor.close()
conn.close()
except IOError, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
首先,我們從數(shù)據(jù)庫中讀取一張圖片數(shù)據(jù):
cursor.execute("SELECT Data FROM Images LIMIT 1")
接著,我們以二進制的寫方式打開一個文件,寫入圖片數(shù)據(jù):
fout = open('image.png','wb')
fout.write(cursor.fetchone()[0])
關(guān)于python中怎么向mysql中存儲圖片就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
當(dāng)前文章:python中怎么向mysql中存儲圖片
分享鏈接:http://www.chinadenli.net/article10/gspjgo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、網(wǎng)站改版、軟件開發(fā)、關(guān)鍵詞優(yōu)化、動態(tài)網(wǎng)站、App開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)