在SQLite中BOOL值的类型是什么?我想在我的表中存储TRUE/FALSE值。

我可以创建一个INTEGER列,并在其中存储0或1的值,但这不是实现BOOL类型的最佳方式。

有办法吗?


当前回答

SQLite没有原生布尔数据类型。根据数据类型文档:

SQLite没有单独的布尔存储类。相反,布尔值存储为整数0 (false)和1 (true)。

其他回答

使用值为0和1的Integer数据类型是最快的。

埃里克瓦的回答更进一步。CHECK约束可以通过强制TEXT数据类型来启用伪布尔列,并且只允许特定于大小写的TRUE或FALSE值。

CREATE TABLE IF NOT EXISTS "boolean_test"
(
    "id" INTEGER PRIMARY KEY AUTOINCREMENT
,   "boolean" TEXT NOT NULL 
        CHECK( typeof("boolean") = "text" AND
               "boolean" IN ("TRUE","FALSE")
        )
);

INSERT INTO "boolean_test" ("boolean") VALUES ("TRUE");
INSERT INTO "boolean_test" ("boolean") VALUES ("FALSE");
INSERT INTO "boolean_test" ("boolean") VALUES ("TEST");

Error: CHECK constraint failed: boolean_test

INSERT INTO "boolean_test" ("boolean") VALUES ("true");

Error: CHECK constraint failed: boolean_test

INSERT INTO "boolean_test" ("boolean") VALUES ("false");

Error: CHECK constraint failed: boolean_test

INSERT INTO "boolean_test" ("boolean") VALUES (1);

Error: CHECK constraint failed: boolean_test

select * from boolean_test;

id  boolean
1   TRUE
2   FALSE

你可以用下面的方法来简化上面的方程:

boolean flag = sqlInt != 0;

如果布尔值的int表示(sqlInt)为0 (false),则布尔值(flag)为false,否则为true。

简洁的代码总是更好的工作:)

数据类型: SQLite没有单独的布尔存储类。相反,布尔值存储为整数0 (false)和1 (true)。

你可以这样把布尔值转换成int值:

int flag = (boolValue)? 1 : 0;

你可以把int转换回boolean,如下所示:

 // Select COLUMN_NAME  values from db. 
 // This will be integer value, you can convert this int value back to Boolean as follows
Boolean flag2 = (intValue == 1)? true : false;

如果你想探索sqlite,这里有一个教程。 我在这里给出了一个答案。这对他们有用。

SQLite没有原生布尔数据类型。根据数据类型文档:

SQLite没有单独的布尔存储类。相反,布尔值存储为整数0 (false)和1 (true)。