python显示数据库内容,如何使用python从mysql数据库显示图片?

I want to display a picture I already saved on the table img, but it gives me an error

cannot identify image file

When it try to open the file_like.

Cursor and connection use the connection and password to mysql database.

With the following code I wanted to display the picture. What's wrong with it, or is there even a better/easier way?

sql1='select * from img'

connection.commit()

cursor.execute(sql1)

data2=cursor.fetchall()

file_like=cStringIO.StringIO(data2[0][0])

img1=PIL.Image.open(file_like,mode='r').convert('RGB')

img1.show()

cursor.close()

解决方案

When using io.BytesIO instead of cstringIO it works fine, also without decoding and encoding. And I also changed type from blob to mediumblob, which allows bigger pictures.

import pymysql

import io

from PIL import Image

connection=pymysql.connect(host="localhost",

user="root",

passwd="root",

db="test")

cursor=connection.cursor()

sql1 = 'select * from table'

cursor.execute(sql1)

data2 = cursor.fetchall()

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

img1=Image.open(file_like2)

img1.show()

cursor.close()

connection.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要使用 Python 的 Flask 框架来实现 Web 应用程序,然后连接到你的数据库。 在 Flask ,你可以使用 Flask-SQLAlchemy 扩展来连接到常见的 SQL 数据库,如 MySQL、PostgreSQL 和 SQLite。这个扩展提供了一个 SQLALCHEMY_DATABASE_URI 配置选项,你需要设置为指向你的数据库的连接字符串。 下面是一个简单的示例,它连接到 SQLite 数据库,并在 Web 页面上显示的数据: ```python from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db' db = SQLAlchemy(app) class Person(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) def __repr__(self): return f'<Person {self.id}>' @app.route('/') def index(): people = Person.query.all() return render_template('index.html', people=people) ``` 在这个示例,我们定义了一个名为 Person 的模型,它映射到数据库的一个表。然后,我们使用 Flask-SQLAlchemy 扩展来连接到 SQLite 数据库,并将其设置为应用程序的默认数据库。 在 index() 视图函数,我们查询所有的 Person 记录,并将它们传递给一个名为 index.html 的模板,该模板将显示这些记录。 下面是 index.html 模板的代码: ```html <!DOCTYPE html> <html> <head> <title>People</title> </head> <body> <table> <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody> {% for person in people %} <tr> <td>{{ person.id }}</td> <td>{{ person.name }}</td> </tr> {% endfor %} </tbody> </table> </body> </html> ``` 在这个模板,我们使用一个名为 people 的变量来迭代所有的 Person 记录,并将它们显示在一个 HTML 表格。 最后,你需要运行这个应用程序,并导航到 http://localhost:5000/,就可以在 Web 页面上看到数据库的数据了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值