android - 向android中的sqlite插入大量数据

标签 android sqlite insert

目前,我必须一次向我的 android 中插入超过 100 亿条数据。但是,内存不足的问题会使程序崩溃。 sqlite 插入测试非常简单。只需使用 for 循环生成 sql 插入命令并按“开始”和“提交”进行处理。

    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 的工作吗?

最佳答案

一些事情:

  1. See my answer here进行批量插入时的一般提示。
  2. 不需要为您的 INSERT 语句提供临时容器(在本例中为 ArrayList<>)。只需使用 beginTransaction()endTransaction()尝试中……终于。
  3. 通过 SQLiteStatement 使用预编译语句与在您的示例中构建每个 INSERT 语句。这是不必要的打击。

快速而肮脏的例子:

// 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;
}

关于android - 向android中的sqlite插入大量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10617524/

相关文章:

iphone - 试图在 iPhone 应用程序更新中覆盖 sqlite 数据库

sql - SQL:使用SELECT将数据插入带有额外列的表中

c++ - seekp()、seekg()、read() 和 write() 在同一个文件上的问题

android - 刷新可扩展 ListView

java - 使用 ArrayList<String> 的 Android Java 字符串数组

android - SQL 查询与搜索算法

postgresql - 根据计数限制插入的通用触发器

android - .jar android 库导入 Xamarin 项目

Android map - 限制在 180 度

mysql - 在连接的情况下是否对条件进行分组在 SQL 中是否重要?