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

使用Flask+SQLAlchemy存数据报错:Connection.execute()获意外参数'job_id'

问题:Flask+SQLAlchemy写入MySQL时出现TypeError的解决方法

我正在学习Flask框架,使用MySQL数据库与SQLAlchemy工具,尝试将用户提交的信息存入名为application的数据库表中,编写的代码如下:

def add_application_to_db(job_id, data):
    with engine.connect() as conn:
        sql = text(
            "INSERT INTO application(id,job_id,fullname,email,linkedin,education,experience,resumeurl) VALUES (:job_id,:fullname,:email,:linkedin,:education,:experience,:resumeurl)"
        )
        conn.execute(
            job_id=job_id,
            fullname=data["fullname"],
            email=data["email"],
            linkedin=data["linkedin"],
            education=data["education"],
            experience=data["experience"],
            resumeurl=data["resumeurl"],
        )

执行代码时出现如下错误:

TypeError: Connection.execute() got an unexpected keyword argument 'job_id'


问题原因

  1. SQLAlchemy的Connection.execute()方法要求先传入编译好的text SQL对象,再传递参数,你直接把参数传给execute(),导致方法无法识别这些关键字参数。
  2. 你的INSERT语句字段列表包含id,但VALUES中没有对应参数,会引发参数不匹配问题(如果id是自增主键,无需手动传入)。

修复后的代码

from sqlalchemy import text

def add_application_to_db(job_id, data):
    with engine.connect() as conn:
        # 若id为自增主键,字段列表移除id;若需手动传入,需补充:id参数
        sql = text(
            "INSERT INTO application(job_id,fullname,email,linkedin,education,experience,resumeurl) VALUES (:job_id,:fullname,:email,:linkedin,:education,:experience,:resumeurl)"
        )
        # 先传入sql对象,再传递参数
        conn.execute(
            sql,
            job_id=job_id,
            fullname=data["fullname"],
            email=data["email"],
            linkedin=data["linkedin"],
            education=data["education"],
            experience=data["experience"],
            resumeurl=data["resumeurl"],
        )
        # 手动提交事务,否则数据不会持久化到数据库
        conn.commit()

额外说明

  • 如果application表的id是自增主键,INSERT操作无需指定该字段,数据库会自动生成值,因此要删除字段列表中的id。
  • 使用engine.connect()创建的连接默认不会自动提交事务,必须调用conn.commit()完成提交,否则数据不会写入数据库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:42:42