如何用Python将MySQL数据展示到HTML?求Py-script替代方案
可行方案及实现步骤
方案一:Flask后端渲染HTML页面
这是最常用的轻量动态展示方案,后端负责数据库操作和页面渲染。
- 步骤1:安装依赖
pip install flask mysql-connector-python - 步骤2:编写Flask后端代码(
app.py)from flask import Flask, render_template import mysql.connector app = Flask(__name__) # 数据库连接配置 def get_db_connection(): return mysql.connector.connect( host='localhost', user='你的用户名', password='你的密码', database='你的数据库名' ) # 初始化数据库和表(首次运行执行) def init_db(): conn = get_db_connection() cursor = conn.cursor() cursor.execute('CREATE DATABASE IF NOT EXISTS test_db;') cursor.execute('USE test_db;') cursor.execute('CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100));') # 插入测试数据(避免重复插入) cursor.execute('INSERT INTO users (name, email) VALUES (%s, %s) ON DUPLICATE KEY UPDATE name=name;', ('Alice', 'alice@example.com')) cursor.execute('INSERT INTO users (name, email) VALUES (%s, %s) ON DUPLICATE KEY UPDATE name=name;', ('Bob', 'bob@example.com')) conn.commit() cursor.close() conn.close() @app.route('/') def index(): conn = get_db_connection() cursor = conn.cursor(dictionary=True) cursor.execute('SELECT * FROM users;') users = cursor.fetchall() cursor.close() conn.close() return render_template('index.html', users=users) if __name__ == '__main__': init_db() app.run(debug=True) - 步骤3:创建HTML模板(需先建
templates文件夹,里面放index.html)<!DOCTYPE html> <html> <head> <title>数据库数据展示</title> </head> <body> <h1>用户列表</h1> <table border="1"> <tr> <th>ID</th> <th>姓名</th> <th>邮箱</th> </tr> {% for user in users %} <tr> <td>{{ user.id }}</td> <td>{{ user.name }}</td> <td>{{ user.email }}</td> </tr> {% endfor %} </table> </body> </html> - 运行:执行
python app.py,访问http://localhost:5000即可查看数据。
方案二:Python生成静态HTML文件
适合数据不需要实时更新的场景,直接用Python读取数据库后生成静态HTML。
- 步骤1:安装依赖
pip install mysql-connector-python - 步骤2:编写生成脚本(
generate_html.py)import mysql.connector # 连接数据库 conn = mysql.connector.connect( host='localhost', user='你的用户名', password='你的密码', database='你的数据库名' ) cursor = conn.cursor(dictionary=True) cursor.execute('SELECT * FROM users;') users = cursor.fetchall() cursor.close() conn.close() # 拼接HTML内容 html_content = f''' <!DOCTYPE html> <html> <head> <title>静态数据展示</title> </head> <body> <h1>用户列表</h1> <table border="1"> <tr> <th>ID</th> <th>姓名</th> <th>邮箱</th> </tr> ''' for user in users: html_content += f''' <tr> <td>{user['id']}</td> <td>{user['name']}</td> <td>{user['email']}</td> </tr> ''' html_content += ''' </table> </body> </html> ''' # 写入文件 with open('output.html', 'w', encoding='utf-8') as f: f.write(html_content) print('静态HTML已生成:output.html') - 运行脚本后,直接打开
output.html就能看到数据。
方案三:FastAPI做API+前端AJAX请求
前后端分离模式,后端提供数据接口,前端通过JS动态拉取数据。
- 步骤1:安装依赖
pip install fastapi uvicorn mysql-connector-python - 步骤2:编写FastAPI后端(
main.py)from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import mysql.connector from pydantic import BaseModel from typing import List app = FastAPI() # 允许跨域请求,方便本地前端测试 app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class User(BaseModel): id: int name: str email: str def get_db_connection(): return mysql.connector.connect( host='localhost', user='你的用户名', password='你的密码', database='你的数据库名' ) @app.get("/users", response_model=List[User]) def get_users(): conn = get_db_connection() cursor = conn.cursor(dictionary=True) cursor.execute('SELECT * FROM users;') users = cursor.fetchall() cursor.close() conn.close() return users if __name__ == '__main__': import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) - 步骤3:编写前端HTML(
index.html)<!DOCTYPE html> <html> <head> <title>API数据展示</title> </head> <body> <h1>用户列表</h1> <table border="1" id="userTable"> <tr> <th>ID</th> <th>姓名</th> <th>邮箱</th> </tr> </table> <script> fetch('http://localhost:8000/users') .then(res => res.json()) .then(users => { const table = document.getElementById('userTable'); users.forEach(user => { const row = table.insertRow(); row.insertCell().textContent = user.id; row.insertCell().textContent = user.name; row.insertCell().textContent = user.email; }); }) .catch(err => console.error('请求失败:', err)); </script> </body> </html> - 运行后端:
python main.py,打开前端HTML即可看到动态加载的数据。
内容的提问来源于stack exchange,提问作者Aleksanyan
相关产品推荐
相关产品推荐

