Skip to content Skip to sidebar Skip to footer

Inserting Image File With Pyqt5 In Mysql Database Table Column

I have been having difficulty in having an image inserted in the MySQL table. I already used the QFileDialog to browse and display the image. However, after saving, whenever I clic

Solution 1:

You should not concatenate the variables to build the query, but rather use the placeholders, otherwise your code will be susceptible to SQL Injection attacks. On the other hand, you must convert the QPixmap, not the text, into bytes using a QBuffer as an intermediary:

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()

Post a Comment for "Inserting Image File With Pyqt5 In Mysql Database Table Column"