mysql处理存储二进制图片

本文介绍如何使用Python的MySQLdb库在MySQL数据库中存储和读取二进制图片数据。通过创建一个名为`Dem_Picture`的表,包含一个`ID`字段和一个`PicData`的MediumBlob类型字段来存储图片。首先,从本地文件读取图片,然后将其写入数据库。接着,从表中读取图片数据并保存到新的文件中。

关键字: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() 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值