如何检查web.py/python中SQL查询结果是否为空
我正在使用web.py框架开发一个网页应用,需要一种方法让web.py/python检查SQL查询的结果是否为空。
这是我现在的函数:
def get_hours():
result = dbconn.query("select * from hours where date < (select max(date) from last_export) order by date DESC")
return result
这个函数按预期工作,但我希望如果查询的结果是空的,它能返回False。我已经知道,Python没有办法直接返回一个可迭代对象(无论它是否为空)中有多少个元素,而不使用计数循环。对我来说,这样做不太合适,因为我不想在返回结果之前就遍历它。
下面是我想通过这个函数实现的一个例子:
def get_hours():
result = dbconn.query("select * from hours where date < (select max(date) from last_export) order by date DESC")
if <result is empty/no rows/nothing to iterate>:
return False
else:
return result
有什么建议吗?
4 个回答
0
试试这个:
def get_hours():
check = False
results = dbconn.query("select * from hours where date < (select max(date) from last_export) order by date DESC")
for result in results:
check = True
#Do stuff here
if check == False:
return false #query returned nothing
0
这里有一个相关的问题,讨论如何判断一个生成器是否一开始就是空的,里面有几个建议可以解决这个问题。根据我所知道的,Python没有简单的方法来测试一个迭代器是否为空。
2
def get_hours():
result = dbconn.query("select * from hours where date < (select max(date) from last_export) order by date DESC")
if result:
return result
else:
return False
这里有一个非常有趣的回答,想了解更多细节可以看看: