【问题标题】:How do I enable strict mode in SQLite 3.31.1?如何在 SQLite 3.31.1 中启用严格模式?
【发布时间】:2022-01-15 04:35:26
【问题描述】:

我正在尝试按照this pagerequire 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> 
$ 

我不仅可以INSERT 错误的数据类型。我也可以SELECT它。

我试过PRAGMA strict=ON;PRAGMA strict=1;。两者都不起作用。我想我没有正确启用严格模式。

如何正确启用严格模式?

【问题讨论】:

  • This page is intended to collect ideas for new error conditions that would be enforced in strict mode, assuming that strict mode is someday implemented.。换句话说,这实际上从未发生过

标签: sql sqlite


【解决方案1】:

根据documentation,将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 上,表创建都会失败,任何以前的版本都将无法打开使用此标志创建的数据库文件,并出现“格式错误的数据库架构”错误。

【讨论】:

  • 请注意,对于旧版本的 SQLite,您可以获得严格的类型检查 by using CHECK constraints
  • 你可以在这里找到:sqlite.org/stricttables.html 那:3.37.0 之前的 SQLite 版本如果在打开数据库后立即设置“PRAGMA writable_schema=ON”,仍然可以读写 STRICT 表文件
猜你喜欢
  • 1970-01-01
  • 2011-11-09
  • 2022-11-16
  • 2013-10-08
  • 2021-12-14
  • 2021-08-07
  • 2011-08-08
  • 1970-01-01
相关资源
最近更新 更多