2012-11-24 40 views
1

我在下面所描述的情景,我的問題是,Android的SQLite的有效補充大量的數據:如果不存在

  • 我怎樣才能讓這個更有效?
    • 我可以改進表結構嗎?
    • 我可以改進查詢/數據訪問和寫作嗎?

目前它可以解析以每秒大約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的來源。 'data'表中的每個條目在'reference'表中至少有一個條目。

我有一個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(); 
} 

回答

0

你可以加快SELECT如果您尚未擁有它們,請在查詢字段上創建索引來查詢。

所有包裝SQL INSERT命令(SQLiteDatabase.insertInsertHelper.execute)的函數都會返回插入記錄的rowid

0

您可以進入異步模式以進行更快的操作。 後,你打開你的sqlite執行這個查詢:

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

當你完成插入你想要的一切,刷新分貝只有簡單的關閉/重新打開:

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

希望這有助於。