Android SQLite database: slow insertion

前端 未结 5 1977
南方客
南方客 2020-11-22 07:26

I need to parse a fairly large XML file (varying between about a hundred kilobytes and several hundred kilobytes), which I\'m doing using Xml#parse(String, ContentHand

5条回答
  •  忘掉有多难
    2020-11-22 07:45

    Since the InsertHelper mentioned by Yuku and Brett is deprecated now (API level 17), it seems the right alternative recommended by Google is using SQLiteStatement.

    I used the database insert method like this:

    database.insert(table, null, values);
    

    After I also experienced some serious performance issues, the following code speeded my 500 inserts up from 14.5 sec to only 270 ms, amazing!

    Here is how I used SQLiteStatement:

    private void insertTestData() {
        String sql = "insert into producttable (name, description, price, stock_available) values (?, ?, ?, ?);";
    
        dbHandler.getWritableDatabase();
        database.beginTransaction();
        SQLiteStatement stmt = database.compileStatement(sql);
    
        for (int i = 0; i < NUMBER_OF_ROWS; i++) {
            //generate some values
    
            stmt.bindString(1, randomName);
            stmt.bindString(2, randomDescription);
            stmt.bindDouble(3, randomPrice);
            stmt.bindLong(4, randomNumber);
    
            long entryID = stmt.executeInsert();
            stmt.clearBindings();
        }
    
        database.setTransactionSuccessful();
        database.endTransaction();
    
        dbHandler.close();
    }
    

提交回复
热议问题