欢迎投稿

今日深度:

Sqlite插入或更新,Sqlite插入更新

Sqlite插入或更新,Sqlite插入更新


本文主要介绍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);

1CREATE 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语句

1 REPLACEINTOhttp_cache(url,content)VALUES('http://www.baidu.com/','<html></html>');

java中可以

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

www.htsjk.Com true http://www.htsjk.com/SQLite/36268.html NewsArticle Sqlite插入或更新,Sqlite插入更新 本文主要介绍Sqlite如何实现插入或更新。 在数据库中我们经常会有这种需求, 插入时,某条记录不存在则插入,存在则更新 。或更新时,某条记录存在...
相关文章
    暂无相关文章
评论暂时关闭