从SQLAlchemy中的表中选择特定列

时间:2014-01-30 15:04:12

标签: python sql select sqlalchemy

我正在尝试从这样的表中选择特定的列:

users = Table('users', metadata, autoload=True)
s = users.select([users.c.email])
results = s.execute()
print results

我收到了这个错误:

> Traceback (most recent call last):   File "my_mailer.py", line 35, in
> <module>
>     s = users.select([users.c.email])   File "/task/__pips__/sqlalchemy/sql/selectable.py", line 175, in select
>     return Select([self], whereclause, **params)   File "/task/__pips__/sqlalchemy/sql/selectable.py", line 2082, in __init__
>     self._whereclause = _literal_as_text(whereclause)   File "/task/__pips__/sqlalchemy/sql/elements.py", line 2745, in
> _literal_as_text
>     "SQL expression object or string expected." sqlalchemy.exc.ArgumentError: SQL expression object or string
> expected.

所以我尝试了这个:

users = Table('users', metadata, autoload=True)
s = users.select('email')
results = s.execute()
print results

得到了回应:

> Traceback (most recent call last):   File "my_mailer.py", line 36, in
> <module>
>     results = s.execute()   File "/task/__pips__/sqlalchemy/sql/base.py", line 124, in execute
>     return e._execute_clauseelement(self, multiparams, params)   File "/task/__pips__/sqlalchemy/engine/base.py", line 1605, in
> _execute_clauseelement
>     return connection._execute_clauseelement(elem, multiparams, params)   File "/task/__pips__/sqlalchemy/engine/base.py", line 761,
> in _execute_clauseelement
>     compiled_sql, distilled_params   File "/task/__pips__/sqlalchemy/engine/base.py", line 874, in
> _execute_context
>     context)   File "/task/__pips__/sqlalchemy/engine/base.py", line 1023, in _handle_dbapi_exception
>     exc_info   File "/task/__pips__/sqlalchemy/util/compat.py", line 185, in raise_from_cause
>     reraise(type(exception), exception, tb=exc_tb)   File "/task/__pips__/sqlalchemy/engine/base.py", line 867, in
> _execute_context
>     context)   File "/task/__pips__/sqlalchemy/engine/default.py", line 388, in do_execute
>     cursor.execute(statement, parameters) sqlalchemy.exc.ProgrammingError: (ProgrammingError) argument of WHERE
> must be type boolean, not type character varying LINE 3: WHERE email

果然,这里的第一个参数是“whereclause”,而不是像其他地方一样的“列”,这反映在the documentation中:

  

此参数不存在于select()的形式上   表

问题:如何使用表格中的select仅选择特定列?通常,为什么地球上的选择上的列参数不可用?我无法理解为什么有人决定使其与标准的选择不同。

2 个答案:

答案 0 :(得分:16)

使用通用select代替Table.select

stmt = select([users.c.email])
result = conn.execute(stmt) 

答案 1 :(得分:1)

使用元数据,您可以执行以下操作:

metadata = MetaData(bind=engine)
tblusers = metadata.tables['users']
tblproducts = metadata.tables['products']
# example 1: only columns you want.
data_users = tblusers.select().with_only_columns([tblusers.c.id, tblusers.c.name]).execute()
# example 2: w/ where & order_by
data_products = tblproducts.select().with_only_columns([tblproducts.c.id, tblproducts.c.price, tblproductos.c.description]).where(tblproducts.c.stock > 0).order_by(tblproducts.c.brand).execute()

好吧......

SqlAlchemy Docs