如何在Flask Python应用中查询MariaDB数据库并将结果渲染到HTML页面
问题原因
你现有代码的核心错误有4个:
cursor.execute()执行SQL后只会返回None,不会直接返回查询结果,需要调用cursor.fetchall()/cursor.fetchmany()等方法才能获取查询到的数据- 你把SQL查询逻辑写在了路由函数外面,项目启动时只会执行1次查询,后续页面刷新不会拉取最新的数据库数据
- 路由函数里第一行就
return result,后面的render_template永远不会被执行,属于不可达死代码 - 没有把查询到的结果传递给HTML模板,模板自然无法渲染数据
修正后的后端代码
from flask import Flask, render_template import mariadb app = Flask(__name__) # 配置数据库参数,单独拎出来方便后续修改 DB_CONFIG = { "host": "IP", "port": 3306, "user": "user", "password": "password", "database": "myDatabase" } @app.route('/') def index(): # 查询逻辑放到路由内部,每次请求都拉取最新数据 conn = None cursor = None try: conn = mariadb.connect(**DB_CONFIG) cursor = conn.cursor() cursor.execute('SELECT * FROM myTable LIMIT 10') # 获取所有查询结果,返回格式为每行数据组成的元组列表 query_result = cursor.fetchall() # 把结果传递给HTML模板,参数名可自定义,模板中用该名称取值 return render_template('index.html', data=query_result) except Exception as e: return f"数据查询出错:{str(e)}" finally: # 查询结束后关闭游标和连接,避免资源泄露 if cursor: cursor.close() if conn: conn.close() if __name__ == "__main__": app.debug = True app.run()
HTML模板(templates/index.html)示例
你可以用Jinja2模板语法遍历传递过来的data参数,渲染成表格形式展示:
<!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> <h2>myTable查询结果(前10条)</h2> <table> <thead> <tr> <!-- 此处列名替换为你myTable表的实际字段名,有多少个字段加多少个th --> <th>ID</th> <th>字段1</th> <th>字段2</th> </tr> </thead> <tbody> {% for row in data %} <tr> <!-- 下标从0开始,对应查询返回的字段顺序,有多少个字段加多少个td --> <td>{{ row[0] }}</td> <td>{{ row[1] }}</td> <td>{{ row[2] }}</td> </tr> {% endfor %} </tbody> </table> </body> </html>
可选优化:返回字典格式结果
如果不想通过下标取值,希望直接用字段名获取对应值,可以在创建游标时指定dictionary=True:
cursor = conn.cursor(dictionary=True)
此时fetchall()返回的每一行是字典格式,模板中可以直接通过字段名取值:
<td>{{ row.id }}</td> <td>{{ row.你的字段名 }}</td>
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

