How to store pictures in mysql in python
This article introduces how to store pictures in python to mysql, the content is very detailed, interested friends can refer to, I hope it can be helpful to you.
The sample code is as follows:
#! / usr/bin/python#-*-coding: utf-8-*-import MySQLdb as mdbimport systry: fin = open ("chrome.png") img = fin.read () fin.close () except IOError, e: print "Error% d:% s"% (e.args [0], e.args [1]) sys.exit (1) try: conn = mdb.connect (host='localhost',user='testuser', passwd='test623' Db='testdb') cursor = conn.cursor () cursor.execute ("INSERT INTO Images SET Data='%s'"%\ mdb.escape_string (img)) conn.commit () cursor.close () conn.close () except mdb.Error, e: print "Error% d:% s"% (e.args [0], e.args [1]) sys.exit (1)
First, we open a picture and read the image data. The code is as follows:
Fin = open ("chrome.png")
Img = fin.read ()
Next, we insert the picture data into the database and use escape_string for special string escape. The code is as follows:
Cursor.execute ("INSERT INTO Images SET Data='%s'"%\
Mdb.escape_string (img))
(13) Reading pictures
In the previous section, we stored the picture in the database, and in this section, we will retrieve it and save it as an image file. Examples in this section are as follows:
#! / usr/bin/python#-*-coding: utf-8-*-import MySQLdb as mdb import systry: conn = mdb.connect (host='localhost',user='testuser', passwd='test623', db='testdb') cursor = conn.cursor () cursor.execute ("SELECT Data FROM Images LIMIT 1") fout = open ('image.png' 'wb') fout.write (cursor.fetchone () [0]) fout.close () cursor.close () conn.close () except IOError, e: print "Error% d:% s"% (e.args [0], e.args [1]) sys.exit (1)
First, we read a picture data from the database:
Cursor.execute ("SELECT Data FROM Images LIMIT 1")
Next, we open a file in binary write mode and write the picture data:
Fout = open ('image.png','wb')
Fout.write (cursor.fetchone () [0])
On how to store pictures in python to mysql to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.