Getting COUNT from sqlalchemy

前端 未结 3 871
闹比i
闹比i 2020-12-11 06:02

I have:

res = db.engine.execute(\'select count(id) from sometable\')

The returned object is sqlalchemy.engine.result.ResultProxy

相关标签:
3条回答
  • 2020-12-11 06:21

    While the other answers work, SQLAlchemy provides a shortcut for scalar queries as ResultProxy.scalar():

    count = db.engine.execute('select count(id) from sometable').scalar()
    

    scalar() fetches the first column of the first row and closes the result set, or returns None if no row is present. There's also Query.scalar(), if using the Query API.

    0 讨论(0)
  • 2020-12-11 06:21

    what you are asking for called unpacking, ResultProxy is an iterable, so we can do

    # there will be single record
    record, = db.engine.execute('select count(id) from sometable')
    # this record consist of single value
    count, = record
    
    0 讨论(0)
  • 2020-12-11 06:30

    The ResultProxy in SQLAlchemy (as documented here http://docs.sqlalchemy.org/en/latest/core/connections.html?highlight=execute#sqlalchemy.engine.ResultProxy) is an iterable of the columns returned from the database. For a count() query, simply access the first element to get the column, and then another index to get the first element (and only) element of that column.

    result = db.engine.execute('select count(id) from sometable')
    count = result[0][0]
    

    If you happened to be using the ORM of SQLAlchemy, I would suggest using the Query.count() method on the appropriate model as shown here: http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=count#sqlalchemy.orm.query.Query.count

    0 讨论(0)
提交回复
热议问题