简体   繁体   中英

How to check if query in SqlAlchemy returns empty result?

I'd like to perform a query like so:

    query = users.select().where(users.column.id == id)
    res = await database.execute(query)

I would then like to add some error handling by checking res . if not res does not seem to be correct. What is the proper way to do this?

You can try taking first object from your query and checking if it is Null like this

result = users.select().where(users.column.id == id).first()
if not result:
    print('query is empty')

The other way editing your code would be

res = query.first()

And then checking if it is Null

Depending on the complexity of your query, it might be cheaper to wrap it inside a SELECT EXISTS(...) than to SELECT... LIMIT 1 , as Antonio describes. PostgreSQL probably knows to treat those queries the same, but according to this answer , not all DBMS might do so.

The beauty of such a solution is that it exists as soon as it finds any result -- it does as little work as possible and is thus as cheap as possible. In SQLAlchemy that would be sa.select([sa.exists(query)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM