很多時候我們為了管理方便會把依稀很小的圖片存入數據庫,有人可能會想這樣會不會對數據庫造成很大的壓力,其實大家可以不用擔心,因為我說過了,是存儲一些很小的圖片,幾K的,沒有問題的!
再者,在這裡我們是想講一種方法,python+ mysql存儲二進制流的方式
這裡用的是Mysqldb,python裡面最常用的數據庫模塊
import MySQLdb
class BlobDataTestor:
def __init__ (self):
self.conn = MySQLdb.connect(host='localhost',user='',passwd='',db='0')
def __del__ (self):
try:
self.conn.close()
except :
pass
def closedb(self):
self.conn.close()
def setup(self):
cursor = self.conn.cursor()
cursor.execute( """
CREATE TABLE IF NOT EXISTS `Dem_Picture` (
`ID` int(11) NOT NULL auto_increment,
`PicData` mediumblob,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
""")
def teardown(self):
cursor = self.conn.cursor()
try:
cursor.execute( "Drop Table Dem_Picture" )
except:
pass
# self.conn.commit()
def testRWBlobData(self):
# 讀取源圖片數據
f = open( "C:\\11.jpg" , "rb" )
b = f.read()
f.close()
# 將圖片數據寫入表
cursor = self.conn.cursor()
cursor.execute( "INSERT INTO Dem_Picture (PicData) VALUES (%s)" , (MySQLdb.Binary(b)))
# self.conn.commit()
# 讀取表內圖片數據,並寫入硬盤文件
cursor.execute( "SELECT PicData FROM Dem_Picture ORDER BY ID DESC limit 1" )
d = cursor.fetchone()[0]
cursor.close()
f = open( "C:\\22.jpg" , "wb" )
f.write(d)
f.close()
# 下面一句的作用是:運行本程序文件時執行什麼操作
if __name__ == "__main__":
test = BlobDataTestor()
try:
test.setup()
test.testRWBlobData()
test.teardown()
finally:
test.closedb()
到這裡python mysql存儲二進制圖片的方法就將完了