我正在尝试跟随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)]
任何想法为什么或我能做些什么呢?
答案 0 :(得分:1)
声明所有类后,请在代码中添加Base.metadata.create_all(engine)
。
这将创建您通过对象声明的所有表。
另外,使用session.commit()
提交您通过session.add(obj)
添加的所有数据