05/10
2013

Sqlite插入或更新

本文主要介绍Sqlite如何实现插入或更新。

在数据库中我们经常会有这种需求,插入时,某条记录不存在则插入,存在则更新。或更新时,某条记录存在则更新,不存在则插入。比如:
人员信息数据库,某个身份证若已经存在,重复插入则更新,否则新增记录。
网页缓存数据库,某个url已经存在,重复插入则更新,否则新增记录。

 

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

 

PS:根据 @MARRBOT 的反馈测试了下, replace into 在表中有数据会先删除整条,再插入要更新的数据,所以主键 id 会变,如果需要 id 不变的还是 insert 和 update 联合,可参考:SQLite – UPSERT *not* INSERT or REPLACE 或 SQLite UPSERT – ON DUPLICATE KEY UPDATE

 

第一步:

新建唯一索引: 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)

相关博客:Android 一键直接查看Sqlite数据库数据

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

10 thoughts on “Sqlite插入或更新

  1. replace 并不会更新,而是用一条新的记录替代之前的记录。比如原来的记录有自增id为1,replace后可能就变成了10。这样当别的表与此表有id的关联时就会出现错误。

  2. Pingback: Android教程收集贴 - 有Bug

  3. insert into …. on duplicate key update 和sqlite的replace into不能相同而言,replace into 实际上是如果表中有数据则先删除整条,再插入要更新的数据。在有些情况下:比如需要更新某个字段而不是整个一行时,就会出问题。