当前位置:   article > 正文

python pyqt5 数据库,Python PyQt5:将图像数据存储到phpmyadmin数据库中

phpmyadmin存放图片

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?

解决方案

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)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/264563
推荐阅读
相关标签
  

闽ICP备14008679号