使用python从MySQL数据库中检索图像

时间:2019-02-28 11:30:55

标签: python mysql

我目前正在一个项目中,我需要在其中检索存储在MySQL数据库中的图像。我尝试了以下代码,但不适用于我。

import mysql.connector
import cv2
from mysql.connector import Error
from mysql.connector import errorcode

def write_file(data, filename):
    # Convert binary data to proper format and write it on Hard Disk
    with open(filename, 'wb') as file:
        file.write(data)


def readBLOB(emp_id,photo):
    print("Reading BLOB from sample")
    try:
        conn = mysql.connector.connect(host='localhost',
                             database='sample',
                             user='susmitha',
                             password='susmitha')
        cursor = conn.cursor()
        query = """SELECT * from sampletable where userid = %s"""
        cursor.execute(query, (emp_id, ))
        record = cursor.fetchall()
        for row in record:
            print("Id = ", row[0])
            image =  row[1]
            print("Storing employee image and bio-data on disk \n")
            write_file(image, photo)

    except mysql.connector.Error as error :
        conn.rollback()
        print("Failed to read BLOB data from MySQL table {}".format(error))

    finally:
        #closing database connection.
        if(conn.is_connected()):
            cursor.close()
            conn.close()
            print("MySQL connection is closed")

readBLOB("user1", "bookobject1.png")

0 个答案:

没有答案