【问题标题】:Android SQLite efficiently add lots of data if not exists如果不存在,Android SQLite 会有效地添加大量数据
【发布时间】:2012-11-12 13:27:13
【问题描述】:

我有下面描述的场景,我的问题是:

  • 如何提高效率?
    • 我可以改进表结构吗?
    • 我可以改进查询/数据访问和写入吗?

目前它每秒可以解析大约 100 个对象。

编辑:通过在“案例 1:”上添加 InsertHelper,现有值的速度提高了,这主要是这种情况。但是,当您需要“last_insert_rowid()”时,我找不到任何有关如何使用它的资源

数据库结构:

data {
  id integer primary key autoincrement
  name text not null
  ...
}

reference {
  id integer (same id as in table1, not unique here tho)
  source text not null
  source_id text not null
}

表“引用”保留来自源的引用和源中的 id 到我的数据库中的 id。 “数据”表中的每个条目在“参考”表中至少有一个条目。

我在流中有一个 JSON,我一次解析和构建一个对象。流可以高达几 MB,包含超过 8000 个对象。构建对象时,它将包含一个引用。

对于我想要构建的每个对象:

if(reference for this object does not exist){
  if(we find the object name in data)
    add to reference with the found id then break
  else
    add to data, get new id, add to reference then break
}

代码看起来像(有点伪代码以便于阅读):

beginTransaction();
try {
  while(parsing next object is successful){
    if("SELECT 1 FROM reference WHERE source = ? and source_id = ?" == null){
      Object[] objects = "SELECT * FROM data WHERE name = ?"
      switch(objects.length){
        case 0:
          "INSERT INTO data (name) VALUES(?)"
          "INSERT INTO reference  (id, source, source_id) VALUES (last_insert_rowid(), ?, ?)"
          break;
        case 1:
          "INSERT INTO reference  (id, source, source_id) VALUES (?, ?, ?)"
          break;
      }
    }
  }
  setTransactionSuccessful();
} finally {
  endTransaction();
}

【问题讨论】:

    标签: android json performance sqlite large-data


    【解决方案1】:

    您可以进入异步模式以获得更快的操作。 打开你的 sqlite 后,执行这个查询:

    yourdb.execSQL("PRAGMA synchronous = OFF");
    

    当您完成插入所需的所有内容后,通过简单的关闭/重新打开来刷新数据库:

    public synchronized SQLiteDatabase flush() {
        if (database != null && database.isOpen()) {
            database.close();
            database = helper.getWritableDatabase();
            return database;
        }
        return database;
    }
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      您可以通过在查找字段上创建索引来加速SELECT 查询(如果您还没有索引)。

      包装 SQL INSERT 命令的所有函数(SQLiteDatabase.insertInsertHelper.execute)返回插入记录的 rowid

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-04
        • 2013-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-30
        • 2011-07-22
        • 1970-01-01
        相关资源
        最近更新 更多