2015-10-21 66 views
0

我正在嘗試關注official SQLalchemy tutorial,但不到一半的時候就會炸燬我的臉。我使用下面的代碼:SQLalchemy無法找到我的表格

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)]

任何想法,爲什麼或者我可以做些什麼呢?

回答

1

請在聲明所有類後,將Base.metadata.create_all(engine)添加到您的代碼中。 這將創建您通過對象聲明的所有表格。

此外,還有一點,用session.commit()提交所有你通過session.add(obj)添加的數據

+0

謝謝!這工作。但由於某些原因,該指南似乎暗示我應該得到一些輸出而不必運行這兩行。它們在指南中提到,但僅在查詢行後面提到。任何想法爲什麼? – TheChymera

+0

本指南給出了有關'Base.metadata.create_all(引擎)'的解釋。請仔細閱讀,http://docs.sqlalchemy.org/zh/rel_1_0/orm/tutorial.html#create-a-schema –