使用sqlalchemy从Mysql DB中选择一个列

时间:2014-02-05 00:50:18

标签: python mysql

如何使用sqlalchemy从单个列中获取值?

在MySQL中

select id from request r where r.product_id = 1;

在Python中

request = meta.tables['request']
request.select(request.c.product_id==1).execute().rowcount   
27L

>>> request.select([request.c.id]).where(request.c.product_id==1).execute()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.freebsd-6.3-RELEASE-i386/egg/sqlalchemy/sql/expression.py", line 2616,     in select
File "build/bdist.freebsd-6.3-RELEASE-i386/egg/sqlalchemy/sql/expression.py", line 305, in select
File "build/bdist.freebsd-6.3-RELEASE-i386/egg/sqlalchemy/sql/expression.py", line 5196, in __init__
File "build/bdist.freebsd-6.3-RELEASE-i386/egg/sqlalchemy/sql/expression.py", line 1517, in _literal_as_text
sqlalchemy.exc.ArgumentError: SQL expression object or string expected.

1 个答案:

答案 0 :(得分:2)

我找到了答案,我必须使用一般选择vs表格选择。

让更多的人觉得这很有用。

conn = engine.connect()
stmt = select([request.c.id]).where(request.c.product_id==1)
conn.execute(stmt).rowcount
27L