首页 > 解决方案 > 如何从我的 Flask python 应用程序查询数据库?

问题描述

到目前为止,我已经成功地将我的代码连接到我要查询的 MariaDB 数据库:

from flask import Flask, render_template, request, flash
import mysql.connector
from datetime import date
import mariadb

app = Flask(__name__)

conn = mariadb.connect(host='IP', port= 3306, user='user', password='password', database='myDatabase')

cursor = conn.cursor()

result = cursor.execute('SELECT * FROM myTable LIMIT 10')

@app.route('/')
def index():
    return result
    return render_template('index.html')
    
# run the app.
if __name__ == "__main__":
    # Setting debug to True enables debug output. This line should be
    # removed before deploying a production app.
    app.debug = True
    app.run()

如何让查询显示在此 Web 应用程序的 HTML 页面上?

标签: pythonmysqlflaskweb-applications

解决方案


你应该在任何教程中得到它。


您必须将结果render_template作为参数发送

@app.route('/')
def index():
    results = result.fetchall() # get all rows 
    return render_template('index.html', data=results)

接下来你可以使用 name datainHTML来显示它。

{{ data }}

您可以for在模板中使用 -loop 对其进行格式化。

<tabel>
{% for row in data %}
<tr>
    {% for item in row %}
      <td>{{ item }}</td>
    {% endfor %}
</tr>
{% endfor %}
</table>

render_template您可以使用任何名称 - 即。all_values=data- 并{{ all_values }}用于HTML


推荐阅读