mysql - 如何使用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'
解决方案
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()
如果您知道您的查询将只返回一行,或者如果您知道您只需要一行,那么您可以直接操作它而不使用循环。
推荐阅读
- sockets - 为什么我们在使用SocketActivityTrigger的时候需要事件StreamSocketListener.ConnectionReceived?
- java - 同等比较后如何删除元素?
- reactjs - 对于 React 应用程序主题,material-ui makeStyles 与 SCSS 架构相比是否有优势?
- python - 在python中为类定义参数
- exe - 无法访问 Windows Installer 服务。如果未正确安装 Windows 安装程序,则可能会发生这种情况
- nginx - 安装了多少nginx权重(不安装应用)
- variables - 使用带有 shell 变量的 find 命令不起作用(没有这样的文件或目录)
- python-3.x - 对以下代码的输出感到困惑
- swift - 有没有办法用 == 来测试 nil
- coq - 如何显示函数的注入性?