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
相关产品推荐
相关产品推荐

