Python3 image conversion binary to MySQL

Source: Internet
Author: User

 mysql is a support for storing pictures in a database, and there is a special field blob (Binary Large object), which is a large binary object field, look at the following code

First, create a table in the database that holds the picture:     Code is as follows: Create TABLE Images (Id INT PRIMARY KEY auto_increment, Data Mediumblob);     Then run the following Python code:       Code as follows: #-*-coding:utf-8-*-import mysqldb as MDB import sys try: &N Bsp   #用读文件模式打开图片     fin = open (". /web.jpg ")     #将文本读入img对象中     img = fin.read ()     #关闭文件     fin.close () except IOError, E:     #如果出错, printing error information     print "Error%d:%s"% (E.args[0],e.args[1])     Sys.exit (1 Try:     #链接mysql, get object     conn = mdb.connect (host= ' localhost ', user= ' root ', passwd= ' root ', db= ') Test ')     #获取执行cursor     cursor = conn.cursor ()     #直接将数据作为字符串, insert database     CURSOR Execute (INSERT into Images SET data= '%s '% mdb.escape_string (IMG))     #提交数据     Conn.commit () &nbs P   #提交之后, then turn off cursor and links     Cursor.close ()     conn.close () except MDB. Error, E:    #若出现异常, printing information     print "Error%d:%s"% (E.args[0],e.args[1])

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.