开发者

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

开发者 https://www.devze.com 2023-01-20 21:45 出处:网络
The questions says it all really. 开发者_StackOverflowI have a table and I want to insert a row if it doesn\'t already exist.

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

精彩评论

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