AlanHorman AlanHorman - 1 year ago 162
Python Question

Python PyQt5: Store image data into a phpmyadmin database

I want to upload a .png file into my database.

fileName = QFileDialog().getOpenFileName()
filePath = str(fileName[0]) # Path of the image data

self.myImage = filePath

connection = pymysql.connect(host = 'localhost',
user = 'root',
db = 'mydatabase',
cursorclass = pymysql.cursors.DictCursor)
cur = connection.cursor()

cur.execute("INSERT INTO mytable VALUES('" + self.myImage + "')")

But something is wrong, because if I look in my local database the image is saved as binary file and I can't open or download it.
What can I do to upload an image into my database properly?

Answer Source

You just need to read the image file and store the data as a blob in the database:

with open(filePath, 'rb') as stream:
    blob =
    cur.execute("INSERT INTO mytable VALUES(%s)", [blob])

To convert the blob into a pixmap:

pixmap = QtGui.QPixmap()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download