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])