首页 > 解决方案 > (sqlite3.OperationalError) 没有这样的表

问题描述

我看到在我的目录中创建的 db 文件,但我无法插入其中。我的问题很基本,有人可以发现明显的吗?

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import models

DB_PATH = 'sqlite:////home/ali/test.db'
engine = create_engine(DB_PATH, echo=True)
Session = sessionmaker(bind=engine)
session = Session()

### Insert data into ProductionRun table ###
prod_run = models.ProductionRun(instance_id=df.instance_id.iloc[0], name=df.profile_name.iloc[0], host=df.host_box.iloc[0], default_config={})

session.add(prod_run)
session.commit()

这是我看到的错误

OperationalError: (sqlite3.OperationalError) no such table: ProductionRun
[SQL: INSERT INTO "ProductionRun" (instance_id, name, host, default_config) VALUES (?, ?, ?, ?)]
[parameters: (1, 'Apple', 'host1', '{}')]
(Background on this error at: http://sqlalche.me/e/13/e3q8)

这里是 ProductionRunmodels.py

class ProductionRun(Base):
    __tablename__ = 'ProductionRun'

    id = Column(Integer, primary_key=True, autoincrement=True)
    instance_id = Column(Integer, nullable=True)
    name = Column(String, nullable=False)
    host = Column(String, nullable=False)
    default_config = Column(JSON, nullable=False)

    status_change = relationship('ProductionRunStatusChange', back_populates='production_run')

标签: pythonsqlitesqlalchemy

解决方案


因为是 Sqlite,所以表类需要在创建数据库之前发生。

DB_PATH = 'sqlite:////home/ali/test.db'
engine = create_engine(DB_PATH, echo=True)
BASE.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

其他堆栈溢出答案的参考

文档


推荐阅读