python+ MySQL how to store binary streams

Source: Internet
Author: User
Many times we will be easy to manage the small picture into the database, some people may think this will not cause great pressure on the database, in fact, we can not worry, because I said, is to store some very small pictures, a few k, no problem!

Furthermore, here we want to talk about a way to python+ MySQL to store binary streams

This is the most common database module in 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 = SE Lf.conn.cursor () Cursor.execute ("" "CREATE TABLE IF not EXISTS ' dem_picture ' (' ID ' I NT (one) not NULL auto_increment, ' Picdata ' Mediumblob, PRIMARY KEY (' ID ')) engine=m              Yisam DEFAULT Charset=utf8 auto_increment=4; "" ") def teardown (self): cursor = Self.conn.cursor () try:cursor.execute (" D ROP Table dem_picture ") Except:pass # Self.conn.commit () def testrwblobdata (       Self): # read source image data F = open ("C:\\11.jpg", "RB")    b = F.read () f.close () # Write picture data to table cursor = Self.conn.cursor () cursor.execute (" INSERT into Dem_picture (picdata) VALUES (%s) ", (Mysqldb.binary (b)) # Self.conn.commit () # reads the picture data in the table and writes to the hard disk File 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 () # below           The function of a sentence is: What to do when running this program file if __name__ = = "__main__": Test = Blobdatatestor () try:test.setup () Test.testrwblobdata () Test.teardown () Finally:test.closedb ()

The way Python MySQL stores binary images here will be done.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.