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?

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 <web.utils.IterBetter instance..> in the interpreter, with no indicate that it's true or false.
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
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.

Comments

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 

Comments

-1

For MySQL Python:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.