久しぶりにSwift以外の話題を。Sqlite3で大量データを一括でinsert,updateしてみます。
以下全て、ターミナルでsqlite3 [tablename]コマンドでdbに入ってからの作業。
テーブル構成
create table tblA (id text,message text,flg boolean,primary key (id));select * from tblA order by id;
(nothing)
初期データ追加
insert into tblA (id,message,flg) values ('100','a',0),('200','b',0);select * from tblA order by id;
100|a|0
200|b|0
キーが重複するinsert文をそのまま実行すると失敗する
insert into tblA (id,message,flg) values ('100','A',1),('300','c',1);
Error: UNIQUE constraint failed: tblA.idselect * from tblA order by id;
100|a|0
200|b|0
insert or replaceだと既存キーの情報は変更される。
insert or replace into tblA (id,message,flg) values ('100','A',1),('300','c',1);select * from tblA order by id;
100|A|1
200|b|0
300|c|1
既存データはuodateではなくて、delete insert。
sqlite> insert or replace into tblA (id,flg) values ('100',1),('300',1);sqlite> select * from tblA order by id;
100||1
200|b|0
300||1
データが多すぎると[Error: too many terms in compound SELECT]エラーとなる。
手元の環境では上限はちょうど500件でした。