如何在 SQLite 中更新 2000 行时最小化时间要求



我有超过20,000行的SQLite。

当我添加新数据( 2000 行)时,需要 2 秒。

但是当我尝试更新相同的 2000 行时,需要将近 10 分钟。

我使用以下代码进行更新

 public int update_ItemPriceDetails(Struct_ItemPrice_Details mStruct_ItemPrice_Details, String ItemId) 
        {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            //values.put(KEY_NAME, contact.getName());
            values.put(Key_ITEM_Id, mStruct_ItemPrice_Details.get_Item_Id()); // Struct_Contact Name
            values.put(Key_PRICE_Id, mStruct_ItemPrice_Details.get_Price_Id()); // Struct_Contact Name
            .
.
.

            // updating row
            int update=db.update(TABLE, values, 
                    Key_PRICE_Id + "=?",
                    new String[] {mStruct_ItemPrice_Details.get_Price_Id()});
        //  db.close();
            return update;
        }


Database_ItemPrice_Details db = getInstance(context);
        SQLiteDatabase DB = db.getWritableDatabase();
        try {
            DB.beginTransaction();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        for(int i=0i<2000;i++)
        {
         update_ItemPriceDetails(List.get(i), "")
        }
    try {       
        Database_ItemPrice_Details_Kolkata db = getInstance(context);
        SQLiteDatabase DB = db.getWritableDatabase();
        DB.setTransactionSuccessful();
        DB.endTransaction();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

步骤#1:不要在循环中调用getWritableDatabase()。在整个代码片段中,应该只有一个调用getWritableDatabase()

步骤#2:正确使用交易:

db.beginTransaction();
try {
  // your SQL
  db.markTransactionSuccessful();
}
catch (Exception e) {
  // do whatever logging you want to do, etc.
}
finally {
  db.endTransaction();
}

可能您拥有的东西不会影响性能,但由于正确的事务对性能非常重要,因此值得研究。特别是在您描述的持续时间内,感觉交易无法正常工作。

步骤#3:正如TobyLL建议的那样,确保在Java中Key_PRICE_Id指示的列上有一个索引。

步骤#4:避免在循环内创建ContentValues,以避免产生过多的垃圾。

步骤#5:使用跟踪视图来确定您在哪里花费剩余时间。

最新更新