这篇“怎么用Python程序实现向MySQL存放图片”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“怎么用Python程序实现向MySQL存放图片”文章吧。
Python 3.7.4 pymysql 8.0.11 MySQL Community Server
以二进制格式读取图片
with open("./test.jpg", "rb") as file:
image = file.read()
存放图片字段的属性为longblog
,即long binary large object
def create_image_table(self):
sql = 'create table if not exists picture ( \
image longblob);'
try:
self.cursor.execute(sql)
self.connection.commit()
except pymysql.Error:
print(pymysql.Error)
将二进制格式的图片数据存入MySQL
def insert_image(self, image):
sql = "insert into picture(image) values(%s)"
self.cursor.execute(sql, image)
self.connection.commit()
以二进制的格式写出图片
def get_image(self, path):
sql = 'select * from picture'
try:
self.cursor.execute(sql)
image = self.cursor.fetchone()[0]
with open(path, "wb") as file:
file.write(image)
except pymysql.Error:
print(pymysql.Error)
except IOError:
print(IOError)
import pymysql
class Database():
'''
Description:
database demo to store image in MySQL RDBMS
Attributes:
None
'''
def __init__(self):
self.connection = pymysql.connect(host='<host name>',user='<user name>',passwd='<password>',db='<database name>',charset='utf8')
self.cursor = self.connection.cursor()
'''
Description:
create table to store images
Args:
None
Return:
None
'''
def create_image_table(self):
sql = 'create table if not exists picture ( \
image longblob);'
try:
self.cursor.execute(sql)
self.connection.commit()
except pymysql.Error:
print(pymysql.Error)
'''
Description:
insert image into table
Args:
image:
image to store
Returns:
None
'''
def insert_image(self, image):
sql = "insert into picture(image) values(%s)"
self.cursor.execute(sql, image)
self.connection.commit()
'''
Description:
get image from database
Args:
path:
path to save image
Returns:
None
'''
def get_image(self, path):
sql = 'select * from picture'
try:
self.cursor.execute(sql)
image = self.cursor.fetchone()[0]
with open(path, "wb") as file:
file.write(image)
except pymysql.Error:
print(pymysql.Error)
except IOError:
print(IOError)
'''
Description:
destruction method
Args:
None
Returns:
None
'''
def __del__(self):
self.connection.close()
self.cursor.close()
if __name__ == "__main__":
database = Database()
# read image from current directory
with open("./test.jpg", "rb") as file:
image = file.read()
database.create_image_table()
database.insert_image(image)
database.get_image('./result.jpg')
以上就是关于“怎么用Python程序实现向MySQL存放图片”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.csdn.net/qq_44486439/article/details/109003727