是否可以强制执行 SQLite 数据类型? [英] Is it possible to enforce SQLite datatypes?

查看:43
本文介绍了是否可以强制执行 SQLite 数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,sqlite 的数据类型与其列无关,而是与数据本身相关联:这实际上意味着您可以将任何数据插入任何列.

From my understanding, sqlite's datatype isn't associated to its column but to the data themselves: this practically means that you can insert any data to any column.

是否可以禁止这种行为?我的意思是,例如,当我不小心尝试将文本插入整数时,我希望 sqlite 引发错误(或至少是警告).

Is it possible to prohibit such a behaviour? I mean, I want sqlite to raise an error (or at least warning) when I accidentally try to insert text to integer, for example.

推荐答案

您可以使用 CHECK 约束和 typeof() 检查实际数据类型:

You can use CHECK constraints and typeof() to check the actual data type:

CREATE TABLE MyTable (
    Col1 INTEGER  CHECK (typeof(Col1) = 'integer'),
    Col2 TEXT     CHECK (typeof(Col2) IN ('text', 'null')
);

这篇关于是否可以强制执行 SQLite 数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆