2012-01-01 37 views
0

我正在研究web.py框架中的web应用程序,并且需要web.py/python来检查sql的结果查询是空的。如何检查是否在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没有办法返回迭代对象中有多少元素(它由dbconn.query返回,无论它是否为空),没有计数for循环。哪一个对我来说是行不通的,因为我不想在返回之前迭代结果。

这里是什么,我想实现与功能相关的例子:

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 

有什么建议?

回答

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 

下面是进一步的细节很有意思的答案:

https://stackoverflow.com/a/2710949/492258

+0

谢谢!正是我在找什么。那么我怎么知道某个函数返回的是什么呢?在解释器中,dbconn.query(“myquery”)和变量'result'都只打印,但没有表明它是真或假。 – simen 2012-01-01 18:35:26

+0

这将无法正常工作,即使查询没有返回任何东西,它仍会继续执行查询中的if部分。因此,请在执行查询之前进行检查。回答如下 – ashishashen 2013-10-29 11:56:24

0

这里的测试发电机是否有任何物品,其中包含几个建议,以解决此限制是一个related (duplicate?) question。据我所知,Python没有一种测试迭代器是否为空的简单方法。

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 
相关问题