使用 SQLAlchemy 获取表中的行数 [英] Get the number of rows in table using SQLAlchemy

查看:85
本文介绍了使用 SQLAlchemy 获取表中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中使用 SQLAlchemy,我想知道如何获取列中的总行数.我定义了变量:

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:

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.

推荐答案

这应该可行

rows = session.query(Congress).count()

与我第一次尝试相关的另一种方式

Another way related to my first try

from sqlalchemy import func
rows = session.query(func.count(Congress.id)).scalar()

这篇关于使用 SQLAlchemy 获取表中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆