目前,我必须一次将超过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;
}
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!