【发布时间】:2021-04-10 14:15:25
【问题描述】:
我看到了在我的目录中创建的 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)
这里是 models.py 中的 ProductionRun
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')
【问题讨论】:
-
如果您在终端中运行
sqlite3 test.db,然后执行SELECT * FROM ProductionRun,它实际上会显示一些结果吗? -
您必须先创建表格,然后再插入表格。
sqlalchemy.MetaData().create_all() -
@jordanm
session.commit()隐式创建数据库。 -
@FedericoBaù 如果我删除 tablename,我会得到
InvalidRequestError: Class <class 'models.ProductionRun'> does not have a __table__ or __tablename__ specified and does not inherit from an existing table-mapped class.。此外,从 test.db 中查询它不会返回任何内容。
标签: python sqlite sqlalchemy