Android SQLite插入优化

最初代码如下,直接执行sql语句,外加事务提升性能:

SQLiteDatabase database = new SQLiteDatabase();  
if (database.isOpen())   
{  
    database.beginTransaction();  
    try {  
         //sql为insert into tableName (name) values ("test")  
        database.execSQL(sql);  
    }  
        database.setTransactionSuccessful();  
    } finally {  
        database.endTransaction();  
    }  
    database.close();  
}

 优化如下: 

SQLiteDatabase database = new SQLiteDatabase();  
//sql为insert into tableName (name) values (?)  
SQLiteStatement sqlListStatment = database.compileStatement(sql);  
if (database.isOpen())   
{  
    database.beginTransaction();  
    try {  
        //index 为1开始索引,value为入库的值  
        //bingXXX为插入XXX类型  
         sqLiteStatement.bindString(index, value);  
         sqLiteStatement.executeInsert();  
    }  
        database.setTransactionSuccessful();  
    } finally {  
        database.endTransaction();  
    }  
    database.close();  
}

相关推荐