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

FastAPI项目访问SQL Server报错:Invalid object name 'testing1'

问题:FastAPI查询SQL Server时提示表不存在错误

错误信息

cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'testing1'. (208) (SQLExecDirectW)")
[SQL: SELECT testing1.id, testing1.name
FROM testing1]
(Background on this error at: https://sqlalche.me/e/14/f405)

相关代码

models.py

from typing import Optional

from sqlmodel import Field, SQLModel


class Testing(SQLModel, table=True):
    __tablename__ = 'testing1'
    
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str

main.py

from fastapi import APIRouter, Depends
from sqlmodel import Session, select

from app.database import get_db
from app.models.testing import Testing

router = APIRouter()


@router.get("/test")
async def get_test(db: Session = Depends(get_db)):
    statement = select(Testing)
    result = db.exec(statement)
    return result.all()

错误原因分析

  • 目标数据库中未创建testing1表:SQLModel不会自动生成数据库表,必须手动执行建表逻辑(比如调用SQLModel.metadata.create_all(engine)),否则数据库中不存在对应表,查询时就会报错。
  • 表名拼写或大小写不匹配:若数据库的排序规则(collation)区分大小写,模型中指定的testing1和实际表名的大小写不一致会导致识别失败;即使不区分大小写,拼写错误也会触发该问题。
  • 数据库或Schema选择错误:数据库连接字符串可能指向了错误的数据库实例,或者表存在于非默认Schema下(比如dbo以外的Schema),此时需要在模型中通过__table_args__ = {"schema": "目标Schema名"}指定正确的Schema。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:11:00