简体   繁体   English

如果情况不适用于 sql 查询 python 的空结果

[英]If case not working for empty result with sql query python

So basically I am trying to retrieve values from a database.所以基本上我试图从数据库中检索值。 My if case is that if the query result which is saved in variable data is None then it should print message data not found.我的 if 情况是,如果保存在变量数据中的查询结果为 None 那么它应该打印未找到的消息数据。 If the value is not none then it should print the data.如果该值不是 none 则它应该打印数据。 My problem is that I am on purpose giving it a value which is not present in the database which means data should be null.我的问题是我故意给它一个数据库中不存在的值,这意味着数据应该为空。 But my if none case is not triggering.但是我的 if none 案例没有触发。 It goes directly to else.它直接转到其他。 I have attached pictures down below.我在下面附上了图片。 Apologies if this question is too basic.如果这个问题太基本,请道歉。 在此处输入图片说明

值为 [] 的数据变量

This is because you are testing if the data variable is am instance of the None object which, from your output, it's not it's a list.这是因为您正在测试数据变量是否是 None 对象的实例,从您的输出来看,它不是一个列表。

So all you need to do is to change your if statement to if not data: which will fix the problem.因此,您需要做的就是将 if 语句更改为if not data:这将解决问题。

Not will pass true for None, False and empty list amongst other things.对于 None、False 和空列表等, Not将传递 true。 see Python Truth Value Testing 参见 Python 真值测试

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

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