Python sqlite3如何使用可能为空的Python值检查相等性

2024-06-02 18:42:05 发布

您现在位置:Python中文网/ 问答频道 /正文

似乎在SQL中null = null返回false。在某些情况下,null表示未知/未指定,但通常null被故意用来表示已知和定义明确的缺席,在这些情况下,我希望null = null是真的。你知道吗

使用sqlite3时,正确的处理方法是什么?像现在这样做:

c.execute('select * from foo where bar = ?', [bar])

如果barNone,则将中断,而我非常希望它返回barnull的每一行。这一切在Haskell的persistent中都能无缝地工作,这正是我在另一端使用的东西(FooBar ==. Nothing),所以我希望Python端也能有类似的干净东西。你知道吗


Tags: 方法fromnonefalseexecutesqlfoobar
1条回答
网友
1楼 · 发布于 2024-06-02 18:42:05

在SQL中NULL = NULL确实是false(NULL实际上是IIRC,但这也是false)。在您的示例中需要的是is操作符'select * from foo where bar is ?'

我猜persistent中的行为是选择=is,这取决于值是否为Maybe a类型,Python没有此类信息(至少在标准库的sqlite模块中没有)。你知道吗

The IS and IS NOT operators work like = and != except when one or both of the operands are NULL. In this case, if both operands are NULL, then the IS operator evaluates to 1 (true) and the IS NOT operator evaluates to 0 (false). If one operand is NULL and the other is not, then the IS operator evaluates to 0 (false) and the IS NOT operator is 1 (true). It is not possible for an IS or IS NOT expression to evaluate to NULL. Operators IS and IS NOT have the same precedence as =.

资料来源:https://www.sqlite.org/lang_expr.html

相关问题 更多 >