Ano*_*ard 5
根据文档,您添加STRICT
到表声明的末尾:
$ sqlite3
SQLite version 3.37.0 2021-11-27 14:13:22
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> CREATE TABLE yay ( col1 TEXT, col2 INT ) STRICT;
sqlite> INSERT INTO yay ( col1, col2 ) VALUES ("this works", "this is the wrong type");
Error: stepping, cannot store TEXT value in INT column yay.col2 (19)
需要注意的是,这是 SQLite 版本 3.37.0 的新功能。在任何以前版本的 SQLite 上,表创建都会失败。并且任何以前的版本都将无法打开使用此标志创建的数据库文件,并出现“格式错误的数据库模式”错误,除非您PRAGMA writable_schema=ON
在打开数据库之前指定了编译指示。
您可以在旧版本的 SQLite 上使用类似的CHECK 约束概念:
SQLite version 3.31.0 2020-01-22 18:38:59
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> CREATE TABLE yay ( col1 TEXT CHECK (typeof(Col1) = 'text'), col2 INT CHECK (typeof(Col2) = 'integer'));
sqlite> INSERT INTO yay ( col1, col2 ) VALUES ("this works", "this is the wrong type");
Error: CHECK constraint failed: yay
更多推荐
模式,如何在,SQLite
发布评论