MySQLdb operation MySQL BLOB value

Source: Internet
Author: User

In general, we store pictures in the file system, but only in the database to store the file path, but sometimes there are special needs: the picture binary into the database.

Today we're using the Python+mysql way.

MYSQL is to support the image into the database, but also corresponding to a dedicated field BLOB (binary Large object), that is, a larger binary object

There is also a larger longblob of binary deposit;

Note here: Try to set the field as large as possible, because if you set the length of the word to be small, the picture will show only part of the situation. Second: If the amount of data is large, try to avoid this way, because MySQL query for big data is very slow.

The following code:

123456789101112131415161718192021222324252627 #!/usr/bin/python#-*- coding: UTF-8 -*- import MySQLdb as mysqlimportsystry:    #读取图片文件    fp =open("./test.jpg")    img =fp.read()    fp.close()exceptIOError,e:    print"Error %d %s"%(e.args[0],e.args[1])    sys.exit(1)try:    #mysql连接    conn =mysql.connect(host=‘localhost‘,user=‘root‘,passwd=‘123456‘,db=‘test‘)    cursor =conn.cursor()    #注意使用Binary()函数来指定存储的是二进制    cursor.execute("INSERT INTO images SET data=‘%s‘" %mysql.Binary(img))    #如果数据库没有设置自动提交,这里要提交一下    conn.commit()    cursor.close()    #关闭数据库连接    conn.close()exceptmysql.Error,e:    print"Error %d %s"%(e.args[0],e.args[1])    sys.exit(1)

MySQLdb operation MySQL BLOB value

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.