开发者

How do I do an atomic INSERT IF NOT EXISTS equivalent in sqlite3?

The questions says it all really.

开发者_StackOverflow

I have a table and I want to insert a row if it doesn't already exist. or should I just do an insert and if the key constraint is violated then ignore it?


Use INSERT OR IGNORE: http://www.sqlite.org/lang_insert.html


Use a trigger that fires before INSERTs and discards the duplicate row, something along the lines of...

CREATE TRIGGER trigger_name
BEFORE INSERT on your_table
FOR EACH ROW WHEN EXISTS (SELECT * FROM your_table WHERE id = NEW.id)
BEGIN
  SELECT RAISE(IGNORE);
END;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜