Android批量插入数据到SQLite数据库

来源:互联网 发布:国家社科期刊数据库 编辑:程序博客网 时间:2024/05/16 07:29

    Android中在sqlite插入数据的时候默认一条语句就是一个事务,因此如果存在上万条数据插入的话,那就需要执行上万次插入操作,操作速度可想而知。因此在Android中插入数据时,使用批量插入的方式可以大大提高插入速度。

    有时需要把一些数据内置到应用中,常用的有以下2种方式:其一直接拷贝制作好的SQLite数据库文件,其二是使用系统提供的数据库,然后把数据批量插入。我更倾向于使用第二种方式:使用系统创建的数据库,然后批量插入数据。批量插入数据也有很多方法,那么那种方法更快呢,下面通过一个demo比较一下各个方法的插入速度。

    1、使用db.execSQL(sql)
    这里是把要插入的数据拼接成可执行的sql语句,然后调用db.execSQL(sql)方法执行插入。

public void inertOrUpdateDateBatch(List<String> sqls) {           SQLiteDatabase db = getWritableDatabase();           db.beginTransaction();           try {               for (String sql : sqls) {                   db.execSQL(sql);               }               // 设置事务标志为成功,当结束事务时就会提交事务               db.setTransactionSuccessful();           } catch (Exception e) {               e.printStackTrace();           } finally {               // 结束事务               db.endTransaction();               db.close();           }   } 
2、使用db.insert("table_name", null, contentValues)
这里是把要插入的数据封装到ContentValues类中,然后调用db.insert()方法执行插入。

        db.beginTransaction(); // 手动设置开始事务        for (ContentValues v : list) {            db.insert("bus_line_station", null, v);        }        db.setTransactionSuccessful(); // 设置事务处理成功,不设置会自动回滚不提交        db.endTransaction(); // 处理完成        db.close();
3、使用InsertHelper类
这个类在API 17中已经被废弃了

InsertHelper ih = new InsertHelper(db, "bus_line_station");        db.beginTransaction();        final int directColumnIndex = ih.getColumnIndex("direct");        final int lineNameColumnIndex = ih.getColumnIndex("line_name");        final int snoColumnIndex = ih.getColumnIndex("sno");        final int stationNameColumnIndex = ih.getColumnIndex("station_name");        try {            for (Station s : busLines) {                ih.prepareForInsert();                ih.bind(directColumnIndex, s.direct);                ih.bind(lineNameColumnIndex, s.lineName);                ih.bind(snoColumnIndex, s.sno);                ih.bind(stationNameColumnIndex, s.stationName);                ih.execute();            }            db.setTransactionSuccessful();        } finally {            ih.close();            db.endTransaction();            db.close();        }
4、使用SQLiteStatement
查看InsertHelper时,官方文档提示改类已经废弃,请使用SQLiteStatement

String sql = "insert into bus_line_station(direct,line_name,sno,station_name) values(?,?,?,?)";        SQLiteStatement stat = db.compileStatement(sql);        db.beginTransaction();        for (Station line : busLines) {            stat.bindLong(1, line.direct);            stat.bindString(2, line.lineName);            stat.bindLong(3, line.sno);            stat.bindString(4, line.stationName);            stat.executeInsert();        }        db.setTransactionSuccessful();        db.endTransaction();        db.close();

下图是以上4中方法在批量插入1万条数据消耗的时间

      

可以发现第三种方法需要的时间最短,鉴于该类已经在API17中废弃,所以第四种方法应该是最优的方法。


0 0
原创粉丝点击