2012-02-26 67 views
12

我試圖通過sqlalchemy tutorial中給出的示例工作,但出現錯誤。據我所知,我正在效仿這封信的例子。這是我迄今爲止的代碼。當我查詢數據庫後,I .first()失敗。sqlalchemy教程示例不起作用

我在0.7.5版和Python 2.7

from sqlalchemy     import Column, Integer, String 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy     import create_engine 
from sqlalchemy.orm    import sessionmaker 

engine = create_engine('sqlite:///:memory:', echo=True) 
engine.execute("select 1").scalar() # works fine 

Session = sessionmaker(bind=engine) 
session = Session() 
Base = declarative_base() 

class User(Base): 
    __tablename__ = 'users' 

    id = Column(Integer, primary_key=True) 
    name = Column(String) 
    fullname = Column(String) 
    password = Column(String) 

    def __init__(self, name, fullname, password): 
     self.name = name 
     self.fullname = fullname 
     self.password = password 

    def __repr__(self): 
     return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password) 

jeff_user = User("jeff", "Jeff", "foo") 
session.add(jeff_user) 

our_user = session.query(User).filter_by(name='jeff').first() # fails here 

jeff_user.password = "foobar" 

session.add_all([ 
       User('wendy', 'Wendy Williams', 'foobar'), 
       User('mary', 'Mary Contrary', 'xxg527'), 
       User('fred', 'Fred Flinstone', 'blah')]) 

session.dirty # shows nothing as dirty 
session.new # shows nothing as new 

以下是錯誤消息

2012-02-25 17:48:33,879 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 
2012-02-25 17:48:33,886 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, password) VALUES (?, ?, ?) 
2012-02-25 17:48:33,886 INFO sqlalchemy.engine.base.Engine ('jeff', 'Jeff', 'foo') 
2012-02-25 17:48:33,887 INFO sqlalchemy.engine.base.Engine ROLLBACK 
Traceback (most recent call last): 
    File "learning_sql.py", line 35, in <module> 
    our_user = session.query(User).filter_by(name='ed').first() # fails here 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2024, in first 
    ret = list(self[0:1]) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 1918, in __getitem__ 
    return list(res) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2092, in __iter__ 
    self.session._autoflush() 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 983, in _autoflush 
    self.flush() 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1559, in flush 
    self._flush(objects) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1630, in _flush 
    flush_context.execute() 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 331, in execute 
    rec.execute(self) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 475, in execute 
    uow 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/mapper.py", line 2291, in _save_obj 
    execute(statement, params) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1405, in execute 
    params) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1538, in _execute_clauseelement 
    compiled_sql, distilled_params 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1646, in _execute_context 
    context) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1639, in _execute_context 
    context) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 330, in do_execute 
    cursor.execute(statement, parameters) 
sqlalchemy.exc.OperationalError: (OperationalError) no such table: users u'INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)' ('jeff', 'Jeff', 'foo') 

預期打印出來是這樣的

>>> our_user = session.query(User).filter_by(name='ed').first() 
BEGIN (implicit) 
INSERT INTO users (name, fullname, password) VALUES (?, ?, ?) 
('ed', 'Ed Jones', 'edspassword') 
SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
FROM users 
WHERE users.name = ? 
LIMIT 1 OFFSET 0 
('ed',) 
>>> our_user 
<User('ed','Ed Jones', 'edspassword')> 

出於某種原因我的代碼應該是SELECT時導致ROLLBACK。

+2

[繼官方ORM教程,我遇到了一個錯誤]的可能重複(http://stackoverflow.com/questions/6710278/following-the-official-orm-tutorial-and-im-running-into-an-error) – 2013-07-16 20:37:29

回答

24

由於數據庫缺少表結構(您顯然錯過了本教程中的這一行,它位於聲明映射小節中),您會看到此錯誤。通過只是你的表/模型定義後加入以下內容來創建模式:

Class User(Base) 
    ... 

# Initialize database schema (create tables) 
Base.metadata.create_all(engine) 
+2

爲了擴展你的答案,在我的情況下我創建了另一個Base,但是因爲這個類來自'Base = declarative_base() '你需要使用與你的對象擴展相同的Base來調用create_all – AsTeR 2013-05-19 22:47:17