0

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?

simen
  • 483
  • 1
  • 6
  • 18

4 Answers4

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

Here is very interesting answer for further details:

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

Community
  • 1
  • 1
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84
  • Thank you! Exactly what I was looking for. So how do I know what a certain function returns? Both dbconn.query("myquery") and the variable 'result' prints only in the interpreter, with no indicate that it's true or false. – simen Jan 01 '12 at 18:35
  • This won't work cause even if the query returns nothing it will still go the the if part in this case.So put a check before executing the query . Answered below – boyfromnorth Oct 29 '13 at 11:56
0

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  
boyfromnorth
  • 958
  • 4
  • 19
  • 41
0

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.

Community
  • 1
  • 1
C. Reed
  • 2,382
  • 7
  • 30
  • 35
-1

For MySQL Python:

data = self.cur.fetchall()

if len(data) == 0:
   self.statusbar.showMessage(" NoRecord her")
else:
   print("avaiable recored")
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135