SQLalchemy找不到我的选项卡

2024-09-28 05:15:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着跟着official SQLalchemy tutorial,但还不到一半,我的脸就爆炸了。我使用以下代码:

from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine, autoflush=False)
session = Session()

from sqlalchemy import Column, Integer, String, Sequence
class Substance(Base):
    __tablename__ = 'substances'

    id = Column(Integer, Sequence("substance_id_seq"), primary_key=True)
    name = Column(String)
    fullname = Column(String)
    hazards = Column(String)

    def __repr__(self):
        return "<Substance(name='%s', fullname='%s', hazards='%s')>" % (self.name, self.fullname, self.hazards)

edta = Substance(name="EDTA", fullname="Ethylenediaminetetraacetic acid", hazards="lala")
session.add(edta)

subs = session.query(Substance).filter_by(name='EDTA').first()
print subs

此操作失败的原因是:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: substances [SQL: u'SELECT substances.id AS substances_id, substances.name AS substances_name, substances.fullname AS substances_fullname, substances.hazards AS substances_hazards \nFROM substances \nWHERE substances.name = ?\n LIMIT ? OFFSET ?'] [parameters: ('EDTA', 1, 0)]

你知道为什么或者我能做些什么吗?在


Tags: namefromimportselfidstringsqlalchemyas
1条回答
网友
1楼 · 发布于 2024-09-28 05:15:20

在声明所有类之后,请将Base.metadata.create_all(engine)添加到代码中。 这将创建通过对象声明的所有表。在

另外,还有一件事,使用session.commit()提交通过session.add(obj)添加的所有数据

相关问题 更多 >

    热门问题