[英]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
.然后我想通过检查
res
添加一些错误处理。 if not res
does not seem to be correct. if not res
似乎不正确。 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您可以尝试从查询中获取第一个 object 并检查它是否像这样 Null
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然后检查是否是 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.根据查询的复杂性,将其包装在
SELECT EXISTS(...)
中可能比SELECT... LIMIT 1
更便宜,正如 Antonio 所描述的。 PostgreSQL probably knows to treat those queries the same, but according to this answer , not all DBMS might do so. PostgreSQL 可能知道将这些查询视为相同,但根据此答案,并非所有 DBMS 都可能这样做。
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)])
在SQLAlchemy中,这将是
sa.select([sa.exists(query)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.