-2

My application uses SQLAlchemy/SQL to query a database. I want to print out the result of the query, but I am getting a <sqlalchemy.engine.result.ResultProxy object in response.

I tried out the suggestions in How to access the results of queries? but I am getting an "Uncaught exception"

See code below:

query = f"SELECT COUNT(DISTINCT id)"\
    f"FROM group"

result = db.session.execute(query)
id_count = result.first()[0]
print(id_count)




user19251203
  • 322
  • 4
  • 13
  • I'm not 100% sure, but try to iterate over `id_count` – Roman Banakh Jun 27 '22 at 14:27
  • @RomanBanakh when I iterate over and print, I get `completed` printed out one letter at a time. I am assuming this is the status of my query, but is there a way to print/log the data of the actual query? – user19251203 Jun 27 '22 at 14:38
  • I think you may find an answer [here](https://stackoverflow.com/questions/17972020/how-to-execute-raw-sql-in-flask-sqlalchemy-app) – Roman Banakh Jun 27 '22 at 16:15

1 Answers1

0

Try this one:

query = f"SELECT COUNT(DISTINCT id)"\
    f"FROM group"

result = db.session.execute(query)
id_count = result.first()

for i in id_count:
    print(i[0]) # Access by positional index
    print(i['my_column']) # Access by column name as a string
    r_dict = dict(i.items()) # convert to dict keyed by column names
Roman Banakh
  • 120
  • 7