首页 > 解决方案 > 如何使用python从数据库中检索图像

问题描述

我想使用 python 从数据库中检索图像,但我在执行此代码时遇到问题

import mysql.connector
import io
from PIL import Image

connection= mysql.connector.connect(
    host ="localhost",
    user ="root",
    passwd ="pfe_altran",
    database = "testes",
    )

cursor=connection.cursor()
sql1 = "SELECT * FROM pfe WHERE id = 1 "
cursor.execute(sql1)
data2 = cursor.fetchall()

file_like2 = io.BytesIO(data2[0][0])

img1=Image.open(file_like2)
img1.show()
cursor.close()
connection.close()

我有这个错误:

file_like2 = io.BytesIO(data2[0][0]) TypeError: a bytes-like object is required, not 'int'

标签: mysql

解决方案


cursor.fetchall()将行列表返回到您的变量,因此您需要使用循环器来处理它

for row in data2:
    file_like2 = io.BytesIO(row[0]) #assumming row[0] contains the byte form of your image

您可以使用cursor.fetchmany(size=1),或者cursor.fetchone()如果您知道您的查询将只返回一行,或者如果您知道您只需要一行,那么您可以直接操作它而不使用循环。


推荐阅读