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ではないため、別のデータベース管理システムに移動する場合は、以下の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
後で...
目標を「列'id'を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');
これらの挿入の1つを繰り返そうとすると、結果がになりError: constraint failed
ます。「id」列に整数以外のものを挿入しようとすると、。で失敗しError: datatype mismatch
ます。