Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sqlalchemy - count rows of result if plain sql query used

I'm using Python 3.9 together with sqlalchemy 1.4.18.

engine = create_engine('sqlite:///somedatabase.sqlite', echo=False)
query = """SELECT ...
    FROM ...
    LEFT JOIN ...
    WHERE ..."""
with engine.connect() as con:
    result = con.execute(query)

How do I count the number of rows the variable result contains in the Python code? I don't want to use COUNT() in SQL. With

print(dir(result))

I found there is a rowcount, however it has always the value -1.

The variable result has the type LegacyCursorResult. Where can find full documentation for this class? The (probably) official docs only mention a close() method: https://docs.sqlalchemy.org/en/14/core/connections.html?highlight=legacycursorresult#sqlalchemy.engine.LegacyCursorResult

Thanks a lot, if somebody can help!

like image 539
Freude Avatar asked Sep 08 '25 04:09

Freude


1 Answers

With SQLAlchemy 1.4+, you can use Result.all to obtain the results as a list, and then call len:

rows = result.all()
count = len(rows)
like image 179
Andrew Eckart Avatar answered Sep 10 '25 13:09

Andrew Eckart