SQLAlchemy:无法获取第一个查询项

时间:2013-11-14 06:12:31

标签: python oracle sqlalchemy

我正在学习SQLAlchemy,我发现这个奇怪的事情。我正在试验一个存储一个人姓名和地址的表格,并让他们使用它:

session.query(User)

为了获得第一项,我尝试了:

session.query(User).first()

抛出DatabaseError

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    session.query(User).first()
  File "build\bdist.win32\egg\sqlalchemy\orm\query.py", line 2275, in first
    ret = list(self[0:1])
  File "build\bdist.win32\egg\sqlalchemy\orm\query.py", line 2142, in __getitem__
    return list(res)
  File "build\bdist.win32\egg\sqlalchemy\orm\query.py", line 2346, in __iter__
    return self._execute_and_instances(context)
  File "build\bdist.win32\egg\sqlalchemy\orm\query.py", line 2361, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 664, in execute
    return meth(self, multiparams, params)
  File "build\bdist.win32\egg\sqlalchemy\sql\elements.py", line 272, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 761, in _execute_clauseelement
    compiled_sql, distilled_params
  File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 874, in _execute_context
    context)
  File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 1023, in _handle_dbapi_exception
    exc_info
  File "build\bdist.win32\egg\sqlalchemy\util\compat.py", line 185, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb)
  File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 867, in _execute_context
    context)
  File "build\bdist.win32\egg\sqlalchemy\engine\default.py", line 376, in do_execute
    cursor.execute(statement, parameters)
DatabaseError: (DatabaseError) ORA-01036: illegal variable name/number
 'SELECT test_user_uid, test_user_name, test_user_address \nFROM (SELECT test_user."uid" AS test_user_uid, test_user.name AS test_user_name, test_user.address AS test_user_address \nFROM test_user) \nWHERE ROWNUM <= :ROWNUM_1' {'ROWNUM_1': 1}

然而,如果我选择所有行,我能够检索我想要的内容,并循环查询对象:

users = [user for user in session.query(User)]
user1 = users[0]

就是这样,我觉得这很奇怪。这是我的映射类:

class User(Base):
    __tablename__ = 'test_user'

    uid = Column(Integer, primary_key = True)
    name = Column(String(50))
    address = Column(String(100))

    def __repr__(self):
        return "<User (%s, %s)"%(self.name, self.address)

我最好的猜测是Session.query().first()正在查找生成的查询的第一行。但是,工作方法检索所有行,并在Python中选择第一行。问题显然来自生成的查询(无效查询)。主要问题是,导致SQLAlchemy创建无效查询的原因是什么?

此外,我注意到SQLAlchemy通过使用子查询进行查询使事情变得更加困难。这种行为是否打算?

我希望我能得到满意的答复,谢谢!

1 个答案:

答案 0 :(得分:1)

嗯,我没多久意识到这一点。事实证明这是一个版本问题,我以前使用cx_Oracle版本5.0.2 10g,我试图将其升级到版本5.1.2 10g,一切正常。

这可能是SQLAlchemy中未记载的错误,我找不到他们提到的地方。

结论:如果要将最新版本的SQLAlchemy(0.9.0b1)与Oracle 10g一起使用,则不应使用早于5.1.2版本的cx_Oracle 10g。

希望这会有所帮助,并感谢你阅读这个问题!