![](/img/trans.png)
[英]web.py - How to turn result of db.query(sql) into list of dict?
[英]How to check if sql query result is empty in web.py/python
我正在 web.py 框架中開發一個 web 應用程序,需要一種 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
有什么建議么?
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
這是有關更多詳細信息的非常有趣的答案:
試試這個:
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
對於 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.