Android SQLite数据库:插入缓慢

23 浏览
0 Comments

Android SQLite数据库:插入缓慢

我需要解析一个相当大的XML文件(大小在几十KB到几百KB之间),我使用Xml#parse(String, ContentHandler)来进行解析。目前我正在使用一个152KB的文件进行测试。\n在解析过程中,我还使用类似以下调用将数据插入到SQLite数据库中:getWritableDatabase().insert(TABLE_NAME, \"_id\", values)。所有这些操作加在一起大约需要80秒来处理这个152KB的测试文件(大约插入了200行数据)。\n当我注释掉所有的插入语句(但保留其他所有操作,例如创建ContentValues等),相同的文件只需要23秒。\n数据库操作有这么大的开销是正常的吗?我能做些什么来改善这个情况吗?

0
0 Comments

Android SQLite数据库:插入缓慢的问题是由于编译SQL插入语句带来的。编译可以加快速度,但需要更多的工作来确保安全,防止可能的注入攻击。

另一种可以加快速度的方法是使用不常见的android.database.DatabaseUtils.InsertHelper类。据我了解,它实际上是对编译插入语句的封装。对于我大型的简单SQLite插入(200K+条记录),从非编译的事务插入到编译的事务插入,速度提高了3倍(每次插入从2ms降到0.6ms)。

示例代码:

SQLiteDatabse db = getWriteableDatabase();
InsertHelper iHelp = new InsertHelper(db, "table_name");
int first_index = iHelp.getColumnIndex("first");
int last_index = iHelp.getColumnIndex("last");
try
{
   db.beginTransaction();
   for(int i=0 ; i

如何在`iHelp.bind(first_index, thing_1);`中添加ContentValue呢?

0
0 Comments

问题出现的原因:使用数据库的insert方法进行插入操作时,性能严重下降。

解决方法:使用SQLiteStatement来替代InsertHelper进行插入操作。

代码示例:

private void insertTestData() {
    String sql = "insert into producttable (name, description, price, stock_available) values (?, ?, ?, ?);";
    dbHandler.getWritableDatabase();
    database.beginTransaction();
    SQLiteStatement stmt = database.compileStatement(sql);
    for (int i = 0; i < NUMBER_OF_ROWS; i++) {
        //generate some values
        stmt.bindString(1, randomName);
        stmt.bindString(2, randomDescription);
        stmt.bindDouble(3, randomPrice);
        stmt.bindLong(4, randomNumber);
        long entryID = stmt.executeInsert();
        stmt.clearBindings();
    }
    database.setTransactionSuccessful();
    database.endTransaction();
    dbHandler.close();
}

这个解决方法能够将插入时间从14.5秒降低到仅需270毫秒,提升了性能。

其他用户的反馈:使用这个方法后,插入时间从78秒降低到了4秒,从4分钟降低到了8秒,从15分钟降低到了45秒,对于一百万行的插入操作能够取得很好的效果。

使用SQLiteStatement替代InsertHelper可以显著提高Android SQLite数据库插入操作的性能。

0
0 Comments

Android SQLite数据库:插入速度慢的问题

在Android开发中,当我们需要往SQLite数据库中插入大量数据时,可能会遇到插入速度慢的问题。下面是一些开发者们提供的解决方法:

一、批量插入数据

使用事务将数据批量插入数据库是提高插入速度的有效方法。以下是一个伪代码示例:

db.beginTransaction();
for (entry : listOfEntries) {
    db.insert(entry);
}
db.setTransactionSuccessful();
db.endTransaction();

这种方式大大提高了我的应用程序的插入速度。

二、使用SQLiteStatement准备语句

在使用事务的基础上,使用SQLiteStatement准备语句可以进一步提高插入速度。以下是一个开发者的评论:

"wrapping my 60 inserts with a transaction increased the performance 10x. wrapping it with a transaction and using a prepared statement (SQLiteStatement) increased it 20x!"

这种方式可以将插入速度提高到原来的20倍。

三、使用InsertHelper

InsertHelper是一个几乎被隐藏的优化工具。这篇博客文章介绍了如何使用InsertHelper来加快插入速度:

Android using inserthelper for faster insertions into sqlite database

根据开发者们的反馈,使用InsertHelper可以显著提高插入速度,但也有少数情况下会稍微降低速度。

通过批量插入数据、使用SQLiteStatement准备语句和InsertHelper等优化方法,我们可以有效地解决Android SQLite数据库插入速度慢的问题。这些方法已经得到了许多开发者的验证,并且在大量数据插入的情况下表现出了显著的性能提升。

0