Python3 picture convert binary into MySQL

Source: Internet
Author: User
First, create a table in the database to hold the picture:
Copy CodeThe code is as follows:


CREATE TABLE Images (Id INT PRIMARY KEY auto_increment, Data Mediumblob);



Then run the following Python code:

Copy the Code code as follows:


#-*-Coding:utf-8-*-
Import MySQLdb as MDB
Import Sys
Try
#用读文件模式打开图片
Fin = Open (".. /web.jpg ")
#将文本读入img对象中
img = Fin.read ()
#关闭文件
Fin.close ()
Except IOError, E:
#如果出错, print error message
Print "Error%d:%s"% (E.args[0],e.args[1])
Sys.exit (1)
Try
#链接mysql, gets the object
conn = mdb.connect (host= ' localhost ', user= ' root ', passwd= ' root ', db= ' test ')
#获取执行cursor
cursor = Conn.cursor ()
#直接将数据作为字符串, inserting a database
Cursor.execute ("INSERT into Images SET data= '%s '"% mdb.escape_string (IMG))
#提交数据
Conn.commit ()
#提交之后, then close the cursor and link
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.