微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在android中将大量数据插入sqlite

目前,我必须一次将超过100亿个数据插入到我的android中.但是,内存不足的问题将使程序崩溃. sqlite插入测试非常简单.只需使用for循环生成sql插入命令,并通过“ begin”和“ commit”将其wrqpped.

    private ArrayList<String> sqlInsertCmd = new ArrayList<String>();
    int QUERIES_TIMES = 10000000;
    private void CreateInsertQueries()
    {
        Random localRandom = new Random();
        int i = 0;
        while (i < QUERIES_TIMES)
        {
            int j = localRandom.nextInt(100000);
            sqlInsertCmd.add("insert into " + TABLE + " (a,b,c) values (" + i + "," + 
            j + ",'" + String.valueOf(j) + "')");
            ++i;
        }
    }

    Then..

    mDB.beginTransaction();
    for (int i=0; i<this.QUERIES_TIMES; i++)
    {
        mDB.execsql(sqlInsertCmd.get(i));
    }
    mDB.setTransactionSuccessful();
    mDB.endTransaction();

有什么想法可以避免内存不足吗?

谢谢大家,但是上面的代码只是一个简单的示例.在我的程序中,它更加复杂.我必须将某些东西存储在容器中(例如hashMap)并动态构建sql语句.我可以创建10个服务,每个服务处理1/10个工作吗?

解决方法:

一些东西:

> See my answer here,了解进行批量INSERT时的一般提示.
>不需要为INSERT语句提供临时容器(在这种情况下为ArrayList<>).只需尝试使用beginTransaction()endTransaction() …最后.
>如示例中所示,通过SQLiteStatement使用预编译语句,而不是构建每个INSERT语句.这是不必要的th动.

快速而肮脏的例子:

// note: untested code used for illustration!
private boolean bulkInsertData(sqliteDatabase db, final String tableName) {
    final int NUM_ROWS = 10000000;

    Random random = new Random();

    try {
        sqliteStatement insstmt = insstmt = db.compileStatement("INSERT INTO " + tableName + " (a, b, c) VALUES (?, ?, ?);");
        db.beginTransaction();
        try {
            for(int i = 0; i < NUM_ROWS; i++) {
                insstmt.bindLong(1, i);
                insstmt.bindLong(2, random.nextInt(100000));
                insstmt.bindString(3, String.valueOf(i));
                insstmt.executeInsert();    //  should really check value here!
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();    
        }
    } catch(sqlException se) {
        return false;
    }

    return true;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐