0

是否可以将图像和值一起存储在数据库中?像在数组中?所以它就像[图像,价值]。我只是想能够访问图像以打印该图像,然后稍后访问该值(例如,如果一个多选问题及其答案是该值,则为图像)。

另外我将如何实现和访问它?我将 Firebase 与 python 的 pyrebase 包装器一起使用,但如果另一个数据库更合适,我愿意接受建议。

4

2 回答 2

0

要在数据库中插入图像,您必须将图像转换为二进制 这是代码

import mysql.connector
from mysql.connector import Error

def convertToBinaryData(filename):
    # Convert digital data to binary format
    with open(filename, 'rb') as file:
        binaryData = file.read()
    return binaryData

def insertBLOB(emp_id, name, photo, biodataFile):
    print("Inserting BLOB into python_employee table")
    try:
        connection = mysql.connector.connect(host='localhost',
                                             database='python_db',
                                             user='pynative',
                                             password='pynative@#29')

        cursor = connection.cursor()
        cursor.execute('create table python_employee(id text, name text, photo BLOB, biodata text)
        sql_insert_blob_query = """ INSERT INTO python_employee
                          (id, name, photo, biodata) VALUES (%s,%s,%s,%s)"""

        empPicture = convertToBinaryData(photo)
        file = convertToBinaryData(biodataFile)

        # Convert data into tuple format
        insert_blob_tuple = (emp_id, name, empPicture, file)
        result = cursor.execute(sql_insert_blob_query, insert_blob_tuple)
        connection.commit()
        print("Image and file inserted successfully as a BLOB into python_employee table", result)

    except mysql.connector.Error as error:
        print("Failed inserting BLOB data into MySQL table {}".format(error))

    finally:
        if (connection.is_connected()):
            cursor.close()
            connection.close()
            print("MySQL connection is closed")

insertBLOB(1, "Eric", "D:\Python\Articles\my_SQL\images\eric_photo.png",
           "D:\Python\Articles\my_SQL\images\eric_bioData.txt")
insertBLOB(2, "Scott", "D:\Python\Articles\my_SQL\images\scott_photo.png",
           "D:\Python\Articles\my_SQL\images\scott_bioData.txt")

sqlite3如果没有安装 mysql,你也可以这样做

于 2020-07-29T11:22:55.017 回答
0

您可以将计算机设置为服务器,并在数据库中存储 [image_path, value]。

于 2020-07-29T11:15:09.377 回答