首页 > 解决方案 > 无法在 html 页面中显示来自 mysql db 的数据

问题描述

这是路由代码:

@app.route("/notice_disp" , methods=['POST','GET'])     
def notice_disp():          
    cur=mysql.connection.cursor()    
    result=cur.execute("SELECT * FROM notices")    
    if result > 0:     
             data=cur.fetchall()      
             cur.close()     
                   return render_template('notice_disp.html',data = data )

这是html代码:

<table>
    <thead>
        <tr>
            <th>notice id</th>
            <th>notice name</th>
            <th>notice</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>

html 页面中的输出: 无法显示数据,我将数据存储在 db 中

标签: pythonhtmlmysqlflask

解决方案


fetchall()返回一个元组列表。因此,您必须使用方括号来访问每个元组的元素:

{% for row in data %}
<tr>
    <td>{{ row[0] }}</td>
    <td>{{ row[1] }}</td>
    <td>{{ row[2] }}</td>
</tr>
{% endfor %}

推荐阅读