`

mysql处理存储二进制图片

阅读更多

关键字:mysql;图片数据导入表

参考url:http://xiaolin0199.iteye.com/blog/585519

  1. import  MySQLdb  
  2.   
  3. class  BlobDataTestor:  
  4.     def  __init__ ( self ):  
  5.         self .conn = MySQLdb.connect(host= 'localhost' ,user= '<your user>' ,passwd= '<your pw>' ,db= '0' )  
  6.   
  7.     def  __del__ ( self ):  
  8.         try :  
  9.             self .conn.close()  
  10.         except  :  
  11.             pass    
  12.   
  13.   
  14.     def  closedb( self ):  
  15.         self .conn.close()  
  16.   
  17.     def  setup( self ):  
  18.         cursor = self .conn.cursor()  
  19.         cursor.execute( """  
  20.             CREATE TABLE IF NOT EXISTS `Dem_Picture` (  
  21.             `ID` int(11) NOT NULL auto_increment,  
  22.             `PicData` mediumblob,  
  23.             PRIMARY KEY (`ID`)  
  24.             ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;  
  25.             """ )  
  26.   
  27.   
  28.   
  29.     def  teardown( self ):  
  30.         cursor = self .conn.cursor()  
  31.         try :  
  32.             cursor.execute( "Drop Table Dem_Picture"  )  
  33.         except :  
  34.             pass    
  35.         # self.conn.commit()    
  36.   
  37.     def  testRWBlobData( self ):   
  38.     # 读取源图片数据                  
  39.         f = open( "C:\\11.jpg"  ,  "rb"  )  
  40.         b = f.read()  
  41.         f.close()  
  42.   
  43.     # 将图片数据写入表    
  44.         cursor = self .conn.cursor()  
  45.         cursor.execute( "INSERT INTO Dem_Picture (PicData) VALUES (%s)"  , (MySQLdb.Binary(b)))  
  46.     # self.conn.commit()    
  47.   
  48.     # 读取表内图片数据,并写入硬盘文件    
  49.         cursor.execute( "SELECT PicData FROM Dem_Picture ORDER BY ID DESC limit 1"  )  
  50.         d = cursor.fetchone()[0 ]  
  51.         cursor.close()  
  52.   
  53.         f = open( "C:\\22.jpg"  ,  "wb"  )  
  54.         f.write(d)  
  55.         f.close()  
  56.   
  57.   
  58. if  __name__ ==  "__main__" :  
  59.   
  60.     test = BlobDataTestor()  
  61.   
  62.     try :  
  63.         test.setup()  
  64.         test.testRWBlobData()  
  65.         test.teardown()  
  66.     finally :  
  67.         test.closedb() 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics