如何处理sqlite准备语句中的空值
How to handle null value in sqlite prepared statement
考虑一个数据库,它对目录树建模,每个文件或文件夹都是一条记录:
CREATE TABLE "tree" (
"id" integer,
"parent_id" integer,
"name" varchar(255),
UNIQUE("parent_id","name"),
PRIMARY KEY("id"),
FOREIGN KEY("parent_id") REFERENCES "tree"("id") on delete cascade
);
根节点 parent_id 设置为 NULL,因为它没有父节点。
为了优化运行时,我想创建一个准备好的语句来查询树:
select * from tree where name=? and parent_id=?
问题是,即使我调用 sqlite3_bind_null,使用上面的语句,select 语句也不会找到带有 parent_id NULL 的行。它仅适用于参数 parent_id is null
.
目前准备了两种语句,一种是NULL,一种是!= NULL,但不是很优雅。
还有其他方法可以实现吗?
你想要 null
-安全平等。在 SQLite 中,您可以使用 is
:
select *
from tree
where name = ? and parent_id is ?
这是如何工作的explained in the documentation:
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).
考虑一个数据库,它对目录树建模,每个文件或文件夹都是一条记录:
CREATE TABLE "tree" (
"id" integer,
"parent_id" integer,
"name" varchar(255),
UNIQUE("parent_id","name"),
PRIMARY KEY("id"),
FOREIGN KEY("parent_id") REFERENCES "tree"("id") on delete cascade
);
根节点 parent_id 设置为 NULL,因为它没有父节点。 为了优化运行时,我想创建一个准备好的语句来查询树:
select * from tree where name=? and parent_id=?
问题是,即使我调用 sqlite3_bind_null,使用上面的语句,select 语句也不会找到带有 parent_id NULL 的行。它仅适用于参数 parent_id is null
.
目前准备了两种语句,一种是NULL,一种是!= NULL,但不是很优雅。 还有其他方法可以实现吗?
你想要 null
-安全平等。在 SQLite 中,您可以使用 is
:
select *
from tree
where name = ? and parent_id is ?
这是如何工作的explained in the documentation:
The
IS
andIS NOT
operators work like=
and!=
except when one or both of the operands areNULL
. In this case, if both operands areNULL
, then theIS
operator evaluates to 1 (true) and theIS NOT
operator evaluates to 0 (false). If one operand isNULL
and the other is not, then theIS
operator evaluates to 0 (false) and theIS NOT
operator is 1 (true).