You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Flask动态表单:Quiz信息无法存入SQLite数据库,求排查

排查与解决方案:Quizzes表无法写入Year和Title的问题

我帮你梳理几个关键排查点,应该能定位到问题:

1. 表单Select标签的默认值写法错误

HTML里的<select>标签不能直接通过value属性设置默认选中项,这种写法是无效的,会导致提交时可能无法正确传递year参数。正确的做法是给对应<option>添加selected属性,修改后的表单代码如下:

<p>Year: <select name="year" id="schoolyear">
    <option value="1" {% if request.form.year == '1' %}selected{% endif %}>7</option>
    <option value="2" {% if request.form.year == '2' %}selected{% endif %}>8</option>
    <option value="3" {% if request.form.year == '3' %}selected{% endif %}>9</option>
    <option value="4" {% if request.form.year == '4' %}selected{% endif %}>10</option>
    <option value="5" {% if request.form.year == '5' %}selected{% endif %}>11</option>
    <option value="6" {% if request.form.year == '6' %}selected{% endif %}>12</option>
    <option value="7" {% if request.form.year == '7' %}selected{% endif %}>13</option>
</select></p>

同时建议你在Flask代码里新增year的打印日志,确认后端是否正确接收到值:

print("Year = " + request.form['year'])

2. 数据库表字段的约束问题

你的quizzes表包含topic字段,但插入操作只传入了yeartitle。如果后续你修改过表结构(比如给topic添加了NOT NULL约束),但没有重新创建表,就会导致插入失败。可以执行以下SQL确认表结构:

PRAGMA table_info(quizzes);

如果topic字段确实是NOT NULL,要么插入时给它一个默认值(比如空字符串),要么修改表结构允许该字段为NULL。

3. 补充调试信息,确认插入动作是否执行

修改你的Flask代码,添加更多调试日志,确认插入操作的执行状态:

try:
    print("register_quizzes")
    db=sqlite3.connect(dbname)
    print(sqlite3.version)
    print("当前连接的数据库文件:", dbname) # 确认是否连接到正确的数据库
    db.row_factory = sqlite3.Row
    cursor = db.cursor()
    # 提取参数并打印
    quiz_year = request.form.get('year')
    quiz_title = request.form.get('title')
    print(f"接收参数:Title={quiz_title}, Year={quiz_year}")
    cursor.execute('''INSERT INTO quizzes (year, title) VALUES (?,?)''', (quiz_year, quiz_title))
    db.commit()
    print("插入完成,影响行数:", cursor.rowcount) # 若为1则说明插入成功
except sqlite3.Error as e:
    print("数据库错误:", e)
except Exception as e:
    print("其他错误:", e)

如果cursor.rowcount返回1,说明数据已经写入,可能是你查询时用了错误的数据库文件;如果是0,说明插入操作根本没执行。

4. 确认路由的请求方法

检查register_quiz对应的路由是否允许POST请求,路由装饰器应该包含methods=['GET', 'POST']

@app.route('/your-route-path', methods=['GET', 'POST'])
def register_quiz():
    # 你的代码逻辑

如果路由只允许GET请求,表单提交的POST数据会被拒绝,自然无法插入数据。

先从这几个点排查,应该能快速找到问题根源。

内容的提问来源于stack exchange,提问作者programmerkane

火山引擎 最新活动