mysql数据在浏览器展示 flask
时间: 2023-02-08 14:40:50 浏览: 110
在 Flask 中,可以使用模板和 HTML 进行数据渲染,并使用 Jinja2 模板引擎来嵌入模板中的变量。
首先,在 Python 中连接 MySQL 数据库,执行 SELECT 语句并检索数据。然后,使用 Flask 提供的 render_template() 函数将数据渲染到 HTML 模板中,并使用 Jinja2 语法在 HTML 中嵌入变量。
最后,使用 Flask 的 @app.route 装饰器创建路由,并在路由中使用 render_template() 函数渲染 HTML 页面。
以下是一个简单的例子:
```
from flask import Flask, render_template
import mysql.connector
app = Flask(__name__)
@app.route('/')
def index():
# 连接 MySQL 数据库
conn = mysql.connector.connect(user='username', password='password', host='hostname', database='database')
cursor = conn.cursor()
# 执行 SELECT 语句并检索数据
cursor.execute("SELECT * FROM table")
data = cursor.fetchall()
# 渲染 HTML 模板并嵌入数据
return render_template('template.html', data=data)
if __name__ == '__main__':
app.run()
```
template.html
```
<html>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for row in data %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
```
阅读全文
相关推荐

















