SQLite implements one line of SQL to update if there is one, insert if not, multiple conditions, complex conditions

SQLite implements one line of SQL to update if there is one, insert if not, multiple conditions, complex conditions

Sample code: https://github.com/miqt/MultiProgressKV/blob/master/MultiProgressKV/src/main/java/com/miqt/multiprogresskv/DBHelper.java

For example, want to implement the following logic

if (db has name ==小明 && 身高 == 170cm)
	update 。。。。
else 
	insert 。。。。

You can refer to the following SQL:

CREATE TABLE [TABLE_NAME](
  [id] INTEGER PRIMARY KEY AUTOINCREMENT, 
  [name] TEXT NOT NULL , 
  [attr] TEXT NOT NULL , 
  [value] TEXT NOT NULL );

CREATE UNIQUE INDEX [TABLE_NAME]
ON [TABLE_NAME](
  [name], 
  [attr]);

CREATE UNIQUE INDEX [TABLE_NAME] declares that only name and attr are repeated to be considered a unique index. This is suitable for scenarios similar to inserting a book. There may only be one title and author of a book, and a single title, And the author himself, may correspond to many books.

The execution of the following statement will have the effect of updating if there is one, and inserting if it is not. The following SQL will only generate one row of results when executed multiple times, and if any column of name or attr is modified, a new one will be inserted.

REPLACE INTO TABLE_NAME
  (
    name ,
    attr ,
    value
  )
VALUES
  (
    '《西游记》' ,
    '作者' ,  
    '吴承恩'
  ) ;

Guess you like

Origin blog.csdn.net/qq_27512671/article/details/111152153