python+ mysql儲存二進位制流的方式

pythontab發表於2012-12-21

很多時候我們為了管理方便會把依稀很小的圖片存入資料庫,有人可能會想這樣會不會對資料庫造成很大的壓力,其實大家可以不用擔心,因為我說過了,是儲存一些很小的圖片,幾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儲存二進位制圖片的方法就將完了


相關文章