您可以使用SQL DDL中的CHECK約束來限制行數。您的應用程序將不得不捕獲嘗試添加太多行所導致的錯誤。還有其他錯誤,您的應用也必須進行陷阱。磁盤已滿,使用NULL等。
關鍵點似乎是保證整數ID號實際上是一個整數。 SQLite的類型親和力可以讓你將無意義插入到一個整數列中。
sqlite> create table foo (n integer);
sqlite> insert into foo values ('wibble');
sqlite> select n from foo;
wibble
但typeof()函數可以保護你免受廢話。
typeof()函數是一個SQLite函數。這不是標準的SQL,所以如果你移動到另一個dbms,你將不得不重寫下面的CHECK約束。 (不太可能,因爲你正在編寫針對Android,但其他人誰看到這可能會在不同的環境中工作。)
create table test_limit (
n integer primary key
check (
(typeof(n)='integer') and
(n >=1 and n <= 10)
)
);
使用typeof(n)
允許插入的整數。範圍條件限制了您可以插入的整數數量。在3.7.9版中進行了簡短的測試。
sqlite> insert into test_limit values (1.13);
Error: datatype mismatch
sqlite> insert into test_limit values (-2);
Error: constraint failed
sqlite> insert into test_limit values ('wibble');
Error: datatype mismatch
sqlite> insert into test_limit values (1);
sqlite> insert into test_limit values (2);
sqlite> insert into test_limit values (17);
Error: constraint failed
後來......
這似乎是一個簡單的,可行的解決辦法,如果你的目標可以表述爲「從1至10包容性的限制欄‘身份證’爲整數」。我對你的代碼有了一些自由,所以我可以直接在SQLite中工作。你應該看看非關鍵列。既然你沒有自然鍵(除了id號以外沒有一組列是唯一的),你真的沒有太多的表。我的SQL插入下面應該使明確問題,但這與將表限制爲10行不同。
create table test_limit (
id integer primary key autoincrement,
site text not null,
address text not null,
username text not null,
password text not null,
check (
typeof(id) = 'integer' and
(id >= 1 and id <= 10)
)
);
-- 10 inserts.
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
insert into test_limit (site, address, username, password)
values ('site', 'address', 'username', 'password');
試圖重複這些插入結果中的一個在Error: constraint failed
。試圖在「id」列中插入除整數之外的任何內容都將失敗,並顯示Error: datatype mismatch
。
觸發器確實存在於Android上的SQLite – dymmeh
@dymmeh很高興知道,謝謝:) – 2012-08-27 16:26:41
「這個限制不能用表格定義強加。」我認爲它可以。你只需要使用SQLite內部函數(不是標準的SQL)來完成它。看到我的答案[這裏](http://stackoverflow.com/a/12148135/562459)。 –