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

Flask中Python连接SQLite仅显示最后一张表的问题求助

解决方案

1. 后端代码:收集所有表的数据到列表

问题出在你之前的代码循环查询时,每次用同一个变量存储结果,导致前面表的数据被覆盖。修改代码把每张表的结果存入列表,一次性传给模板:

from flask import Flask, render_template
import sqlite3

app = Flask(__name__)

@app.route('/')
def show_all_tables():
    conn = sqlite3.connect('你的数据库名.db')
    cursor = conn.cursor()
    
    # 替换成你要展示的所有表名
    target_tables = ['表1', '表2', '表3']
    all_table_info = []
    
    for table_name in target_tables:
        # 查询当前表的所有数据
        cursor.execute(f"SELECT * FROM {table_name}")
        # 获取表头字段名
        column_names = [col[0] for col in cursor.description]
        # 获取表内数据
        table_data = cursor.fetchall()
        # 把当前表的信息存入列表
        all_table_info.append({
            'name': table_name,
            'columns': column_names,
            'rows': table_data
        })
    
    conn.close()
    # 将所有表的数据传给前端模板
    return render_template('index.html', tables=all_table_info)

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

2. 前端模板:循环渲染所有表

在templates/index.html中,遍历传入的tables列表,逐个渲染每张表:

<!DOCTYPE html>
<html>
<head>
    <title>所有数据表</title>
    <style>
        table {border-collapse: collapse; margin: 25px 0;}
        th, td {border: 1px solid #ccc; padding: 10px;}
        th {background-color: #f5f5f5;}
        h3 {color: #333;}
    </style>
</head>
<body>
    {% for table in tables %}
        <h3>{{ table.name }}</h3>
        <table>
            <thead>
                <tr>
                    {% for col in table.columns %}
                        <th>{{ col }}</th>
                    {% endfor %}
                </tr>
            </thead>
            <tbody>
                {% for row in table.rows %}
                    <tr>
                        {% for item in row %}
                            <td>{{ item }}</td>
                        {% endfor %}
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    {% endfor %}
</body>
</html>

问题根源

你之前的代码大概率是在循环中每次用同一个变量存储单张表的数据,比如data = cursor.fetchall(),循环结束后这个变量只保留了最后一张表的结果,传给模板后自然只能显示最后一张表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:19:58