Flask查询MySQL同id数据仅显示第一条,如何输出全部匹配记录
问题原因
出现单条记录无法展示全部的问题由两处代码逻辑导致:
- 后端查询使用
cursor.fetchone()方法,仅会返回匹配结果的第一条数据 - 前端模板仅编写了固定的单条表格行结构,无法适配多条记录的渲染需求
解决方案
你确实需要配合for循环实现多记录渲染,这是Flask+Jinja2栈下最简便高效的实现方案,修改代码如下:
1. 修改Flask路由代码
将fetchone替换为fetchall获取所有匹配的交易记录:
@app.route('/user_history') def user_history(): cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) if 'loggedin' in session: cursor.execute('SELECT * FROM inforamtion WHERE id = %s', [session['id']]) # fetchall返回所有匹配结果组成的列表 accounts = cursor.fetchall() return render_template('user_history.html', accounts=accounts) return redirect(url_for('login'))
2. 修改HTML模板代码
新增Jinja2 for循环遍历所有记录生成表格行,同时补充空数据提示逻辑:
{% block content %} <table class="table table-striped"> <tr> <th>From</th> <th>To</th> <th>Transffered Amount</th> </tr> {% for account in accounts %} <tr> <td>{{ account['from1'] }}</td> <td>{{ account['to1'] }}</td> <td>{{ account['amount1'] }}</td> </tr> <!-- 无匹配记录时触发else分支 --> {% else %} <tr> <td colspan="3">暂无交易记录</td> </tr> {% endfor %} {% endblock %}
注意事项
你代码中查询的表名inforamtion拼写疑似有误(正确拼写为information),如果后续出现查询为空的情况可以优先核对表名配置。
其他可选方案
如果不想使用模板层for循环,也可以在后端将所有记录拼接为HTML表格字符串,直接传递给模板渲染,但该方案耦合度高、维护成本高,不推荐使用。
内容的提问来源于stack exchange,提问作者Vikram Kale
相关产品推荐
相关产品推荐

