最快和最有效的方式在Android的pre填充数据库 [英] Fastest and most efficient way to pre-populate database in Android
问题描述
如果你想pre-填充数据库(SQLite的)在Android中,这不是容易,因为人们可能认为。
If you want to pre-populate a database (SQLite) in Android, this is not that easy as one might think.
所以,我发现本教程也就是常此处引用的堆栈溢出为好。
So I found this tutorial which is often referenced here on Stack Overflow as well.
但我真的不喜欢的pre-填充数据库,因为你需要从数据库处理程序的控制和创建的文件你自己的方式。我想preFER不要碰文件系统,并让数据库处理程序做一切自己。
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)/资产,其中包含的语句来填充值:
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');
...
但调用execSQL()在处理程序的onCreate()并没有真正的工作。看来,/资产的文件不得有超过1MB的execSQL()只执行第一条语句(迈克 - 虎)。
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).
你会怎么做做pre-填充数据库?
What would you do do pre-populate the database?
推荐答案
我建议如下:
- 包装所有的INSERT逻辑成一个事务(BEGIN ... COMMIT,或通过<一href="http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#beginTransaction()"相对=nofollow>的BeginTransaction() ... <一个href="http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#endTransaction()"相对=nofollow> endTransaction()方法的API)
- 在前面已经提出,利用绑定API和回收对象。
- 请不要创建索引,直到在此之后批量插入就完成了。
- Wrap all of your INSERT logic into a transaction (BEGIN... COMMIT, or via the beginTransaction()... endTransaction() APIs)
- As already suggested, utilize the bind APIs and recycle objects.
- Don't create any indexes until after this bulk insert is complete.
此外看一看在sqlite3的更快的批量插入?
Additionally take a look at Faster bulk inserts in sqlite3?
这篇关于最快和最有效的方式在Android的pre填充数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!