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

Flask项目MySQL查询ID在网页下拉框显示为空的问题排查

问题原因

下拉选项渲染为空和字体颜色无关,核心是三处代码错误:

  • 字段名不匹配:SQL查询返回的字段是CID(来自CYCLIST表)、SID(来自STAGE表),但模板中取值写的是row['cyclist']、x['stage'],字段名完全对应不上,模板引擎取不到值自然输出空内容。
  • 结果对象传参错误:直接把SQLAlchemy的执行结果游标传给模板,在调用con.close()关闭数据库连接后,游标无法再读取数据,必须在连接关闭前把结果转为普通Python数据结构再传入模板。
  • HTML语法错误:模板中<form>标签闭合位置错误,写在了表格内部,会导致表单提交行为异常。
修复代码

修改app.py

from flask import Flask, render_template, request
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import create_engine, text

app = Flask(__name__)

@app.route("/")
def index():
    dialect = "mysql+pymysql"
    username = "root"
    psw = ""
    host = "localhost"
    dbname = "cyclic_championship"

    engine = create_engine(f"{dialect}://{username}:{psw}@{host}/{dbname}")
    
    try:
        con = engine.connect()
        # 新版SQLAlchemy执行原生SQL需用text()包裹语句
        query1 = text("SELECT CID FROM CYCLIST")
        query2 = text("SELECT SID FROM STAGE")
        # 连接关闭前将结果转为字典格式的列表,避免游标失效
        cyclist_ids = con.execute(query1).mappings().all()
        stage_ids = con.execute(query2).mappings().all()
        con.close()
        return render_template("index.html", rows=cyclist_ids, rowss=stage_ids)
    except SQLAlchemyError as e:
        error = str(e.__dict__['orig'])
        return render_template('error.html', error_message=error)

if __name__ == "__main__":
    app.run(debug=False, port=5001)

注意:如果没装pymysql驱动,先执行pip install pymysql安装,否则会报数据库驱动缺失错误。

修改index.html对应部分

把两个下拉选框的取值字段改成SQL实际返回的字段名,同时修正form标签的闭合位置:

<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1 style="text-align:center"> Cyclist Position by stage</h1>

<form action="/">
    <table style="border:0px solid black;margin-left:auto;margin-right:auto;background-color: lightgray;width: 350px;height: 250px;">
    <tr >
        <td style="text-align:center"><label for="cyclist" >Cyclist Id:</label></td>
    </tr>
    <tr>
    <td style="text-align:center;">
        <select title="cyclist" id="cyclist" name="cyclist" style="width: 225px;">
            {% for row in rows %}
                <option value="{{ row['CID'] }}" style="color:#000000">{{ row['CID'] }}</option>
            {% endfor %}
        </select>
    </td>
    </tr>
    <tr>
        <td style="text-align:center"><label for="stage">Stage Id:</label></td>
    </tr>
    <tr>
    <td style="text-align:center">
        <select title="stage" id="stage" name="stage" style="width: 225px;color: black;">
            {% for x in rowss %}
                <option value="{{ x['SID'] }}" style="color: black;">{{ x['SID'] }}</option>
            {% endfor %}
        </select>
    </td>
    </tr>
    <tr>
        <td style="text-align:center"><input type="submit" value="Send" style="background-color:lightgreen;width: 225px;border: 1px;"></td>
    </tr>
  </table>
</form> <!-- 把form闭合标签移到表格外面,修正嵌套错误 -->

</body>
</html>

修改后重启服务,下拉框就能正常显示从数据库读取的ID值了。

内容的提问来源于stack exchange,提问作者Ali H.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 04:18:24