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


很多時候我們為了管理方便會把依稀很小的圖片存入數據庫,有人可能會想這樣會不會對數據庫造成很大的壓力,其實大家可以不用擔心,因為我說過了,是存儲一些很小的圖片,幾K的,沒有問題的!

 

再者,在這里我們是想講一種方法,python+ mysql存儲二進制流的方式

 

這里用的是Mysqldb,python里面最常用的數據庫模塊

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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 ):    
     # 讀取源圖片數據                  
         =  open "C:\\11.jpg"  "rb"  )   
         =  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"  )   
         =  cursor.fetchone()[ 0 ]   
         cursor.close()   
   
         =  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存儲二進制圖片的方法就將完了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM