views:

412

answers:

4

Is it possible to do SELECT * in sqlalchemy?

Edit: Specifically, SELECT * WHERE foo=1

A: 

If you don't list any columns, you get all of them.

query = users.select()
query = query.where(users.c.name=='jack')
result = conn.execute(query)
for row in result:
    print row

Should work.

S.Lott
What if I want a WHERE clause?
mike
Added the where class stuff. You should look at http://www.sqlalchemy.org/docs/05/sqlexpression.html#selecting for better advice.
S.Lott
+1  A: 

Turns out you can do:

sa.select('*', ...)
mike
+4  A: 

Is no one feeling the ORM love of SQLALchemy today? The presented answers correctly describe the lower level interface that SQLAlchemy provides. Just for completeness this is the more-likely (for me) real-world situation where you have a session instance and a User class that is orm mapped to the users table.

for user in session.query(User).filter_by(name='jack'):
     print user
     # ...

And this does an explicit select on all columns.

Ali A
"more-likely?" Really? Perhaps for you. But based on this question, perhaps not so likely for others.
S.Lott
S.Lott: you are exactly right, I felt uncomfortable writing this.
Ali A
S.Lott: updated to reflect that I really was talking about my own experiences. Anyone reading the comments should note that I was mostly referring to the basic setups of things like Webapps with common frameworks like Pylons which can use SQLA.
Ali A
@Ali A: Since I'm a Django ORM guy, I almost spewed the Django answer to this. I'm all about ORM.
S.Lott
A: 

Where Bar is the class mapped to your table and session is your sa session:

bars = session.query(Bar).filter(Bar.foo == 1)
adam