简体   繁体   中英

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.

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. 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. 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

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.

For MySQL Python:

data = self.cur.fetchall()

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

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