Saturday, April 3, 2021

Storing to & Retrieving images from MySQL

# https://www.youtube.com/watch?v=NwvTh-gkdfs

''' Should have a table "images" under test as:

CREATE TABLE images

( id    INT(45) NOT NULL AUTO_INCREMENT PRIMARY KEY,

  photo LONGBLOB NOT NULL

);

'''


import mysql.connector as mc


conn = mc.connect(host="localhost", user="root", password="bont", database="test")

cur = conn.cursor()


def InsertBlob(Path):

  with open(Path, "rb") as inn:

    s = inn.read()

  sql = "INSERT INTO images (Photo) VALUES (%s)"

  cur.execute(sql, (s, ))

  conn.commit()


def RetrieveBlob(ID):

  sql = "SELECT * FROM images WHERE id = '{0}'"

  cur.execute(sql.format(str(ID)))

  result = cur.fetchone()[1]

  storeFilePath = "img{0}.jpg".format(str(ID))

  print(result)

  with open(storeFilePath, "wb") as out:

    out.write(result)

    out.close()


print("1. Insert Image")

print("2. Read Image")

choice = input("Enter your choice: ")

if choice == '1':

  path = input("Enter file path: ")

  InsertBlob(path)

elif choice == '2':

  userId = input("Enter ID: ")

  RetrieveBlob(userId)


No comments:

Post a Comment