目前,我必须一次向我的 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 的工作吗?
最佳答案
一些事情:
- See my answer here进行批量插入时的一般提示。
- 不需要为您的 INSERT 语句提供临时容器(在本例中为 ArrayList<>)。只需使用 beginTransaction()和 endTransaction()尝试中……终于。
- 通过 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/