最快和最有效的方式在Android中预填充数据库 [英] Fastest and most efficient way to pre-populate database in Android

查看:244
本文介绍了最快和最有效的方式在Android中预填充数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你想在Android中预先填充数据库(SQLite),这不是那么容易想象。

If you want to pre-populate a database (SQLite) in Android, this is not that easy as one might think.

所以我发现本教程,此处通常也参考Stack Overflow。

So I found this tutorial which is often referenced here on Stack Overflow as well.

但是我真的不喜欢这种预填充数据库的方式,因为你从数据库处理程序中获取控制并自己创建文件。我更喜欢不碰文件系统,让数据库处理程序自己做一切。

But I don't really like that way of pre-populating the database since you take the control from the database handler and create the files yourself. I would prefer to not touch the file system and let the database handler do everything on its own.

所以我想,可以做的是在数据库处理程序中创建数据库onCreate()像往常一样,然后加载一个文件(.sql)从/ assets中包含的语句来填充值:

So what I thought one could do is create the database in the database handler's onCreate() as usual but then load a file (.sql) from /assets which contains the statements to fill in the values:

INSERT INTO testTable (name, pet) VALUES ('Mike', 'Tiger');
INSERT INTO testTable (name, pet) VALUES ('Tom', 'Cat');
...

但是在处理程序的onCreate()中调用execSQL真的工作。看起来/ assets文件不能超过1MB,execSQL()只执行第一个语句(Mike - Tiger)。

But calling execSQL() in the handler's onCreate() doesn't really work. It seems that the /assets file must not have more than 1MB and the execSQL() only executes the first statement (Mike - Tiger).

-

推荐答案


  • INSERT 所有逻辑封装到一个事务中( BEGIN ... COMMIT 通过 beginTransaction() ... < a href =http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#endTransaction() =nofollow> endTransaction() API)

  • 如已经建议的,使用绑定API和循环对象

  • >此批量插入已完成。

    1. Wrap all of your INSERT logic into a transaction (BEGIN... COMMIT, or via the beginTransaction()... endTransaction() APIs)
    2. As already suggested, utilize the bind APIs and recycle objects.
    3. Don't create any indexes until after this bulk insert is complete.

    另外,请查看在sqlite3中更快的批量插入?

    这篇关于最快和最有效的方式在Android中预填充数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆