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

SQLAlchemy+SQLite查询始终返回空列表问题求助

SQLite数据库查询始终返回空列表问题

按照FastAPI官方教程编写代码,查询本地已有SQLite数据库时始终返回空列表(计数为0),相关信息如下:

相关代码

路由实现

@app.get("/")
def root(db: Session = Depends(get_db)):
    return get_all_podcasts(db)

CRUD逻辑(crud.py)

def get_all_podcasts(db: Session, limit: int = 100):
    pods = db.query(Podcast).limit(limit).all()
    return pods

数据模型定义

@dataclass
class Podcast(Base):
    __tablename__ = "podcasts"

    id: int
    title: str
    description: str
    image: str

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    description = Column(String, index=True)
    image = Column(String, index=True)

    category = relationship("Category", back_populates="podcast")
    drops = relationship("Drops", back_populates="podcast")

数据库配置(database.py)

SQLALCHEMY_DATABASE_URL = "sqlite:///podpill.db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}, echo=True, echo_pool=True
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

执行日志

2023-04-03 12:45:11,886 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-04-03 12:45:11,894 INFO sqlalchemy.engine.Engine SELECT podcasts.id, podcasts.title, podcasts.description, podcasts.image 
FROM podcasts
 LIMIT ? OFFSET ?
2023-04-03 12:45:11,894 INFO sqlalchemy.engine.Engine [generated in 0.00019s] (100, 0)
INFO:     127.0.0.1:61643 - "GET / HTTP/1.1" 200 OK
2023-04-03 12:45:11,896 INFO sqlalchemy.engine.Engine ROLLBACK

已尝试的排查措施

  • 确认模型字段与数据库podcasts表结构完全匹配
  • 手动执行日志中生成的SQL语句,可正常查询到数据
  • 改用SQLAlchemy 2.0新语法执行查询,问题未解决
  • 检查应用启动时的PRAGMA查询,无返回结果

恳请提供可行的排查方向或解决办法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:17:32