How to update sqlite table if records exist else insert?

后端 未结 3 423
孤独总比滥情好
孤独总比滥情好 2021-01-17 01:06

This may be duplicate question but am confused as am new for sql and android am getting response from server need to save it in sqlite db if values in the table already exis

3条回答
  •  执笔经年
    2021-01-17 01:37

    replace is just like insert, it just checks if there is duplicate key and if it is it deletes the row, and inserts the new one, otherwise it just inserts

    you can do this if there is for example unique index of (Model_Task_List.KEY_taskid) and if you type the following command

    REPLACE INTO Model_Task_List.KEY_table(Model_Task_List.KEY_taskid,Model_Task_List.KEY_task,Model_Task_List.KEY_username,Model_Task_List.KEY_subject) VALUES ('111',3,50,90 )
    

    and there already exists a row with Model_Task_List.KEY_taskid= '111' it will be replaced

    CREATE UNIQUE INDEX idx_name_type ON Model_Task_List.KEY_table(Model_Task_List.KEY_taskid)
    

    EDIT: a quick note - REPLACE always DELETES and then INSERTs, so it is never a very good idea to use it in heavy load because it needs exclusive lock when it deletes, and then when it inserts

    some of the database engines have

    INSERT ... ON DUPLICATE KEY UPDATE ...

    Link

提交回复
热议问题