Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select only some columns in SQLAlchemy?

This is my python code:

 cx=sqlalchemy.create_engine(u"mysql://username:password@ipaddress/database?charset=utf8")

 metadata=sqlalchemy.MetaData(cx)
 orm_obj=sqlalchemy.Table(u'I_POI',metadata,autoload=True)


 sql=orm_obj.select(u'poi_id,poi_name').where(u'poi_id>1 and poi_id>0').limit(3).offset(0)

 resultz=sql.execute()
 for i in resultz:
     print i

[DB] I_POI Table:poi_id,poi_name,poi_data1,poi_data2......poi_data10

I do it with existing database,but "select()" is no work..It still return total columns.
I want to get only some columns,please help me.

like image 540
scott1028 Avatar asked Aug 12 '12 00:08

scott1028


People also ask

How do I SELECT in SQLAlchemy?

The select() method of table object enables us to construct SELECT expression. The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method. Here, we have to note that select object can also be obtained by select() function in sqlalchemy.

What is difference between filter and filter by in SQLAlchemy?

The second one, filter_by(), may be used only for filtering by something specifically stated - a string or some number value. So it's usable only for category filtering, not for expression filtering. On the other hand filter() allows using comparison expressions (==, <, >, etc.)

How do I drop a column in SQLAlchemy?

There is a tool called sqlalchemy-migrate which works this way; you have a Table object, you say, "table. remove_column(col)", and it emits an "ALTER TABLE" which drops that column.

How do I get column names in SQLAlchemy?

To access the column names we can use the method keys() on the result. It returns a list of column names.


1 Answers

here is the code that works for me:

from sqlalchemy import select
from sqlalchemy.sql import and_

results = select([orm_obj.c.poi_id, orm_obj.c.poi_name])\
    .where(and_(orm_obj.c.id > 1, orm_obj.c.id < 100)).execute()
for id, name in results:
    print id, name
like image 156
Flynn Avatar answered Oct 01 '22 23:10

Flynn