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

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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.