You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Flask实现数据库数据动态表格生成的技术问询

用Flask动态生成数据库数据对应的网页表格

完全不需要预先添加大量表格行再控制可见性,Flask结合Jinja2模板引擎就能轻松实现根据数据库数据动态生成对应行数的表格,下面是具体实现方案:

方案一:Flask后端+Jinja2模板渲染(推荐)

1. Flask后端代码

先从数据库查询数据,把查询结果传递给前端模板。这里以SQLite为例,你可以替换为MySQL、PostgreSQL等其他数据库的连接方式:

from flask import Flask, render_template
import sqlite3

app = Flask(__name__)

@app.route('/')
def show_table():
    # 连接数据库
    conn = sqlite3.connect('your_database.db')
    conn.row_factory = sqlite3.Row  # 让查询结果可通过列名访问
    cursor = conn.cursor()
    # 查询目标表所有数据
    cursor.execute('SELECT * FROM your_table')
    data = cursor.fetchall()
    conn.close()
    # 将数据传给前端模板
    return render_template('table.html', data=data)

if __name__ == '__main__':
    app.run(debug=True)

2. Jinja2模板(templates/table.html)

在模板里用for循环遍历后端传来的数据,动态生成表格行:

<!DOCTYPE html>
<html>
<head>
    <title>动态数据表格</title>
    <style>
        table {border-collapse: collapse; width: 80%; margin: 20px auto;}
        th, td {border: 1px solid #ddd; padding: 8px; text-align: left;}
        th {background-color: #f2f2f2;}
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <!-- 替换为你的数据库实际列名 -->
                <th>列名1</th>
                <th>列名2</th>
                <th>列名3</th>
            </tr>
        </thead>
        <tbody>
            <!-- 循环遍历数据,自动生成对应行数 -->
            {% for row in data %}
            <tr>
                <td>{{ row['column1'] }}</td>
                <td>{{ row['column2'] }}</td>
                <td>{{ row['column3'] }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

不管数据库返回50行还是更多数据,模板都会自动生成对应数量的表格行,无需手动写死标签。

方案二:前端JS动态生成(前后端分离场景)

如果需要更灵活的前端交互,可以让Flask提供API接口,前端用JavaScript获取数据后动态创建表格:

1. Flask API接口

@app.route('/api/data')
def get_data():
    conn = sqlite3.connect('your_database.db')
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM your_table')
    data = cursor.fetchall()
    conn.close()
    # 将数据转为字典列表,以JSON格式返回
    return {'data': [dict(row) for row in data]}

2. 前端HTML+JS

<!DOCTYPE html>
<html>
<head>
    <title>JS动态生成表格</title>
    <style>
        table {border-collapse: collapse; width: 80%; margin: 20px auto;}
        th, td {border: 1px solid #ddd; padding: 8px; text-align: left;}
        th {background-color: #f2f2f2;}
    </style>
</head>
<body>
    <table id="data-table">
        <thead>
            <tr>
                <th>列名1</th>
                <th>列名2</th>
                <th>列名3</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <script>
        // 从API获取数据并动态生成表格行
        fetch('/api/data')
            .then(response => response.json())
            .then(result => {
                const tbody = document.querySelector('#data-table tbody');
                result.data.forEach(row => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${row.column1}</td>
                        <td>${row.column2}</td>
                        <td>${row.column3}</td>
                    `;
                    tbody.appendChild(tr);
                });
            });
    </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者solac34

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 10:22:27