0

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 + "')")  
    connection.commit()

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?

2
  • 1
    An image file is nothing but bytes - just like any other file. Why can't you open or download it? What have you tried? What specifically went wrong? The code in your question does not upload a file; it just inserts a file-path into the database. Commented Oct 29, 2016 at 15:38
  • Yes, this is why it doesn't work. If I want to download the "wrong path file", it comes out a small binary file and not an image file. You can't open it and it's useless. I want to upload a file and not the path. I thought the path refers to the file, but it doesn't. What must I do to upload the image file? Commented Oct 29, 2016 at 18:15

1 Answer 1

1

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 = stream.read()
    cur.execute("INSERT INTO mytable VALUES(%s)", [blob])

To convert the blob into a pixmap:

pixmap = QtGui.QPixmap()
pixmap.loadFromData(blob)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.