Home  >  Article  >  Database  >  How to use Python to read pictures from the database using MySQL

How to use Python to read pictures from the database using MySQL

WBOY
WBOYforward
2023-05-29 19:22:121108browse

Read the picture from the database

import MySQLdb as mdb
import sys
try:
#连接 mysql,获取连接的对象
conn = mdb.connect('localhost', 'root', 'root', 'test');
cursor = conn.cursor()
#执行查询该图片字段的 SQL
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:
#捕获 IO 的异常 ,主要是文件写入会发生错误
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)

The above is the detailed content of How to use Python to read pictures from the database using MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete