I am using SQLAlchemy in Python, and I want to know how to get the total number of rows in a column. I have variables defined:
我在Python中使用SQLAlchemy,我想知道如何获取列中的总行数。我有变量定义:
engine = sqlalchemy.create_engine(url, ehco=False)
Session = sqlalchemy.orm.sessionmaker(bind=engine)
Session = session()
metadata = sqlalchemy.MetaData(engine)
Base = declarative_base(metadata=metadata)
# A class representing the shape_congress_districts_2012 table
class Congress(Base):
__tablename__ = 'shape_congress_districts_2012'
id = geoalchemy.Column(sqlalchemy.Integer, primary_key=True)
name = geoalchemy.Column(sqlalchemy.Unicode)
geom = geoalchemy.GeometryColumn(geoalchemy.Polygon(2))
geom_simple = geoalchemy.GeometryColumn(geoalchemy.Polygon(2))
area = geoalchemy.Column(sqlalchemy.Float)
state_id = geoalchemy.Column(sqlalchemy.Integer)
census_year = geoalchemy.Column(sqlalchemy.Date)
geoalchemy.GeometryDDL(Congress.__table__)
I want to determine the total number of rows in the table without having to wait a whole bunch of time querying the database. Currently, I have a bit of code:
我想确定表中的总行数,而不必等待一大堆时间查询数据库。目前,我有一些代码:
rows = session.query(Congress).all()
Then I can access them from list, but this requires me to load everything into memory at once.
然后我可以从列表中访问它们,但这需要我立即将所有内容加载到内存中。
1 个解决方案
#1
55
This should work
这应该工作
rows = session.query(Congress).count()
EDIT: Another way related to my first try
编辑:与我的第一次尝试相关的另一种方式
from sqlalchemy import func
rows = session.query(func.count(Congress.id)).scalar()
#1
55
This should work
这应该工作
rows = session.query(Congress).count()
EDIT: Another way related to my first try
编辑:与我的第一次尝试相关的另一种方式
from sqlalchemy import func
rows = session.query(func.count(Congress.id)).scalar()