在 MySQL 数据库 table 列中使用 PyQt5 插入图像文件

Inserting image file with PyQt5 in MySQL database table column

我一直难以在 MySQL table 中插入图像。我已经使用 QFileDialog 来浏览和显示图像。但是,保存后,每当我单击检查 table 列中的 BLOB 时,都不会保存任何内容。我已经尝试进行一些研究,并且我意识到我在 SQL 命令中将图像作为文本文件插入是错误的。请老师们,重组我下面的代码并实现我插入图像的目标的最佳做法是什么?

class TestReg(QWidget):

    def __init__(self):
        super().__init__()
        self.ui = Ui_TestRegForm()
        self.ui.setupUi(self)

        #Calling browseImage
        self.ui.browse_btn.clicked.connect(self.browseImage)

        #Calling insertPers
        self.ui.save_btn.clicked.connect(self.insertPers)

    #Browses person's picture and displays using label called image_label
    def browseImage(self):
        file_name = QFileDialog.getOpenFileName(self, 'Open File', 'c:\', 'Image Files (*.png *.jpg *gif)')
        image_path = file_name[0]
        pixmap = QPixmap(image_path)
        self.ui.image_label.setPixmap(QPixmap(pixmap))

    #Inserts person into database
    def insertPers(self):
        try:
            con = MySQLdb.connect(host="localhost", user="root", password="", database="somedb")
            with con:
                cur = con.cursor()
                cur.execute("INSERT INTO persons(name, photo)" "VALUES('%s', '%s')" % (''.join(self.ui.name_edit.text()), ''.join(self.ui.image_label.text()))
                con.commit()
                self.displayDialog(QMessageBox.Information, "Registration", "Person has been added successfully")
        except MySQLdb.Error as e:
            self.displayDialog(QMessageBox.Warning, "Registration", str(e))
        except TypeError as e:
            self.displayDialog(QMessageBox.Warning, "Registration", str(e))
        except ValueError as e:
            self.displayDialog(QMessageBox.Warning, "Registration", str(e))

您不应连接变量来构建查询,而应使用占位符,否则您的代码将容易受到 SQL 注入攻击。另一方面,您必须使用 QBuffer 作为中介将 QPixmap 而不是文本转换为字节:

con = MySQLdb.connect(host="localhost", user="root", password="", database="somedb")
with con:
    cur = con.cursor()
    name = self.ui.name_edit.text()
    buff = QBuffer()
    buff.open(QIODevice.WriteOnly)
    pixmap = QPixmap(self.ui.image_label.pixmap())
    pixmap.save(buff, "PNG")
    binary_img = buff.data().toBase64().data()
    cur.execute("INSERT INTO persons(name, photo) VALUES (%s, %s)", (name, binary_img))
    con.commit()