我试着跟着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)]
你知道为什么或者我能做些什么吗?在
在声明所有类之后,请将
Base.metadata.create_all(engine)
添加到代码中。 这将创建通过对象声明的所有表。在另外,还有一件事,使用
session.commit()
提交通过session.add(obj)
添加的所有数据相关问题 更多 >
编程相关推荐