0

I am currently working on a project in which I need to retrieve images that are stored in MySQL database. I tried the following code, but it's not working for me.

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")
Sush
  • 3
  • 3

0 Answers0