Sqlite插入或更新

在数据库中我们经常会有这种需求,插入时,某条记录不存在则插入,存在则更新。或更新时,某条记录存在则更新,不存在则插入。比如:

人员信息数据库,某个身份证若已经存在,重复插入则更新,否则新增记录。

网页缓存数据库,某个url已经存在,重复插入则更新,否则新增记录。

在mysql中可以使用replace into或是insert into …. on duplicate key update实现。在sqlite中我们同样可以使用replace into实现。分为两步,下面以http cache表为例,仅包含三个字段,主键_id, url, content

第一步:新建唯一索引: CREATE UNIQUE INDEX mycolumn_index ON mytable (myclumn);

CREATE UNIQUE INDEX unique_index_url ON http_cache (url);

java中可以直接在SQLiteOpenHelper的OnCreate中添加

public class DbHelper extends SQLiteOpenHelper { 

   public void onCreate(SQLiteDatabase db) {

        db.beginTransaction();

        try {

            db.execSQL(DbConstants.CREATE_HTTP_RESPONSE_TABLE_UNIQUE_INDEX.toString());

            db.setTransactionSuccessful();

        } finally {

            db.endTransaction();

        }

    }

}

第二步:调用replace into语句

REPLACE INTO http_cache (url, content) VALUES ('http://www.baidu.com/', '<html></html>' );

java中可以

sQLiteDatabase.replace(DbConstants.HTTP_RESPONSE_TABLE_TABLE_NAME, null, contentValues)

更多见:Trinea Android开发笔记

原文地址:https://www.cnblogs.com/trinea/p/3079169.html