您好,登錄后才能下訂單哦!
本篇內容介紹了“如何用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存放圖片”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。