SqlAlchemy, cannot retrieve the counting of a table rows

Question:

I am trying to store the number of row of the table "computers" this way:

with my_db.connect() as conn:

    result = conn.execute(text("SELECT COUNT(id) FROM computers;"))

    return result

But when I print "result" I get:

sqlalchemy.engine.cursor.LegacyCursorResult object

Any idea ?

Asked By: ailauli69

||

Answers:

Try: return result.one() to get one row of values from the result cursor

Answered By: brunson

Use the connection’s scalar method:

with my_db.connect() as conn:

    result = conn.scalar(text("SELECT COUNT(id) FROM computers;"))

    return result

.scalar will return the first column of the first row of the result.

Answered By: snakecharmerb
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.