天天看点

SQLite3 类型系统

大多数数据库使用静态的严格的类型系统,列的类型在创建表的时候就已经指定了。SQLite使用动态的类型系统,列的类型由值决定。

1.存储类型

以下是SQLite的存储类型,SQLite中存储的每个值都对应以下一种存储类型

NULL: NULL value

Integer: 值是signed integer 类型,大小可以是1,2,3,4,6,8bytes

REAL:  浮点类型

TEXT: 以UTF-8, UTF-16BE or UTF-16LE编码存储的字符类型

BLOB: 二进制数据

Integer primary key 列是个例外??

布尔类型: SQLite中没有定义布尔类型,而是以Integer 存储布尔值,0(false), 1(true)

Date and time 类型

SQLite中也没有定义日期时间类型,日期时间可以用TEXT, REAL, or INTEGER存储

TEXT:  存储为字符串("YYYY-MM-DD HH:MM:SS.SSS").

REAL: as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.

INTEGER: as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

2. SQLite Type Affinity

用于自动检测值的类型,以下列举Affinity如何决定类型的规则

(1)    如果类型声明中有int,则使用INTEGER affinity.

(2)    如果类型声明中有"CHAR", "CLOB", or "TEXT", 则使用Text affinity

(3)    如果类型声明中有BLOB或没有指定类型,则使用affinity NONE

(4)    如果类型声明中有"REAL", "FLOA", or "DOUB", 则使用 REAL affinity

(5)    否则使用Numeric affinity

SQLite 有以下几种affinity

  • TEXT
  • NUMERIC
  • INTEGER
  • REAL
  • NONE

例子

CREATE TABLE t1(

t TEXT, -- text affinity by rule 2

nu NUMERIC, -- numeric affinity by rule 5

i INTEGER, -- integer affinity by rule 1

r REAL, -- real affinity by rule 4

no BLOB -- no affinity by rule 3

);

-- Values stored as TEXT, INTEGER, INTEGER, REAL, TEXT.

INSERT INTO t1 VALUES('500.0', '500.0', '500.0', '500.0', '500.0');

SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;

text|integer|integer|real|text

-- Values stored as TEXT, INTEGER, INTEGER, REAL, REAL.

DELETE FROM t1;

INSERT INTO t1 VALUES(500.0, 500.0, 500.0, 500.0, 500.0);

SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;

text|integer|integer|real|real

-- Values stored as TEXT, INTEGER, INTEGER, REAL, INTEGER.

DELETE FROM t1;

INSERT INTO t1 VALUES(500, 500, 500, 500, 500);

SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;

text|integer|integer|real|integer

-- BLOBs are always stored as BLOBs regardless of column affinity.

DELETE FROM t1;

INSERT INTO t1 VALUES(x'0500', x'0500', x'0500', x'0500', x'0500');

SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;

blob|blob|blob|blob|blob

-- NULLs are also unaffected by affinity

DELETE FROM t1;

INSERT INTO t1 VALUES(NULL,NULL,NULL,NULL,NULL);

SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;

null|null|null|null|null

3. 类型比较

NULL < TEXT< BLOB < INTEGER or REAL, INTEGER,REAL之间用数学方法比较, BLOB之间用memcmp()函数比较

memcmp函数原型

int memcmp ( const void * ptr1, const void * ptr2, size_t num );

比较两个指针指向内存的前num个byte

比较之前的类型转换

  • (INTEGER, REAL or NUMERIC) 和 (TEXT or NONE)比较,则TEXT, NONE会被转换成NUMERIC
  • TEXT和NONE比较,则NONE会被转换成TEXT
  • 其他情况直接比较

参考

http://www.sqlite.org/datatype3.html (Datatypes in SQLite Version 3)