是否必须关闭数据库? [英] Is it essential to close the database?

查看:125
本文介绍了是否必须关闭数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在谷歌的记事本为例,他们似乎没有关闭数据库,至少在的onDestroy()。

In Google's Notepad Example, they don't seem to close the database, at least not in onDestroy().

什么是关闭它的宗旨,我真的需要?有没有一个开放的数据库占用显著的内存?我发现,关闭它的onDestroy留下的漏洞,如果有运行的可能试图访问该活动结束后,所有的线程。

What is the purpose of closing it, and do I really need to? Does an open database take up significant memory? I have found that closing it in onDestroy leaves vulnerabilities if there are any threads running that might try to access it after the Activity is finished.

推荐答案

如果您不关闭数据库连接,它们会导致内存泄漏随着时间。

If you don't close the database connections, they'll cause memory leaks over time.

记事本例子并使用 startManagingCursor ,但你仍然需要明确地关闭数据库连接。运行记事本的例子为,是在连续编辑几个音符,你会看到,它开始抛出警告和错误的LogCat中。 (在较大的应用程序,你也将开始看到内存泄漏检测警告。)

The Notepad example does use startManagingCursor, but you still need to explicitly close the db connection. Run the Notepad example as-is and edit several notes in succession, you'll see that it starts throwing Warnings and Errors in LogCat. (In larger applications, you'll also start to see Memory Leak Detection warnings.)

W/SQLiteCompiledSql(  302): Releasing statement in a finalizer. Please ensure that you explicitly call close() on your cursor: INSERT INTO notes(body, title) VALUES(?, ?);
W/SQLiteCompiledSql(  302): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
W/SQLiteCompiledSql(  302):     at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:62)
...
W/SQLiteCompiledSql(  302):     at dalvik.system.NativeStart.main(Native Method)
E/Database(  302): close() was never explicitly called on database '/data/data/com.android.demo.notepad3/databases/data' 
E/Database(  302): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
E/Database(  302):  at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1810)
...
E/Database(  302):  at dalvik.system.NativeStart.main(Native Method)

您提到,关闭它在的onDestroy()中仍在运行的任何非UI线程留下的漏洞。如果你使用的AsyncTask,您可以检查使用的getStatus 你的任务这些线程的状态。

You mentioned that closing it in onDestroy() "leaves vulnerabilities" in any non-UI threads that are still running. If you're using AsyncTask, you can check the status of of these threads using getStatus on your tasks.

if ( myAsyncTask.getStatus() == AsyncTask.Status.FINISHED ){
    mDbHelper.close();
}

然后关闭的 onPostExecute 方法连接你的的AsyncTask

希望有所帮助......

Hope that helps...

这篇关于是否必须关闭数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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