require a datatype on every table column and enforce those types.我正在尝试按照此页面启用严格模式。
$ sqlite3 ./a_new_database.sqlite
SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
sqlite> PRAGMA strict=ON;
sqlite> CREATE TABLE yay ( col1 TEXT, col2 INT );
sqlite> INSERT INTO yay ( col1, col2 ) VALUES ("this works", "this is the wrong type");
sqlite> SELECT * from yay;
this works|this is the wrong type
sqlite>
$
Run Code Online (Sandbox Code Playgroud)
我不仅可以INSERT错误的数据类型。我也可以SELECT啊
我已经尝试过了PRAGMA strict=ON;并且PRAGMA strict=1;。两者都不起作用。我认为我没有正确启用严格模式。
如何正确启用严格模式?
根据文档,您添加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)
Run Code Online (Sandbox Code Playgroud)
需要注意的是,这是 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2460 次 |
| 最近记录: |