简体   繁体   English

如何在 web.py/python 中检查 sql 查询结果是否为空

[英]How to check if sql query result is empty in web.py/python

I'm working on a web application in the web.py framework and need a way for web.py/python to check if the result of a sql query is empty.我正在 web.py 框架中开发一个 web 应用程序,需要一种 web.py/python 的方法来检查 sql 查询的结果是否为空。

Here's my current function:这是我目前的功能:

def get_hours():
    result = dbconn.query("select * from hours where date < (select max(date) from last_export) order by date DESC")
    return result

This works as expected, but I want the function to return False if the result of the query is empty.这按预期工作,但如果查询结果为空,我希望该函数返回 False。 I already know that python has no way of returning how many elements there is in a iterable object(which is returned by the dbconn.query no matter if it's empty or not), without a count for loop.我已经知道 python 无法返回可迭代对象中有多少个元素(由 dbconn.query 返回,无论它是否为空),没有计数 for 循环。 Which to me wouldn't work since i don't want the result to be iterated BEFORE it's returned.这对我来说不起作用,因为我不希望结果在返回之前被迭代。

Here's an example of what I want to achieve with the function:这是我想用这个函数实现的一个例子:

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

Any suggestions?有什么建议么?

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

Here is very interesting answer for further details:这是有关更多详细信息的非常有趣的答案:

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

Try this:试试这个:

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  

Here's a related (duplicate?) question on testing whether a generator has any items, which contains several suggestions to work around this limitation.这是有关测试生成器是否具有任何项目的相关(重复?)问题,其中包含解决此限制的一些建议。 As far as I know, Python does not have a simple way of testing whether an iterator is empty.据我所知,Python 没有简单的方法来测试迭代器是否为空。

For MySQL Python:对于 MySQL Python:

data = self.cur.fetchall()

if len(data) == 0:
   self.statusbar.showMessage(" NoRecord her")
else:
   print("avaiable recored")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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