简体   繁体   English

Android sqlite保持连接打开

[英]Android sqlite leaving connection open

I create a SQLiteDatabase instance and call getReadableDatabase() or getWritableDatabase() and manipulate data that way but I never close the database via db.close() . 我创建一个SQLiteDatabase实例,并调用getReadableDatabase()getWritableDatabase()并以这种方式操作数据,但我从未通过db.close()关闭数据库。 Is it bad to not close it? 不关闭它不好吗? I tried adding db.close() to my onStop() or onDestroy() methods but it just force closes. 我尝试将db.close()添加到我的onStop()onDestroy()方法中,但是它只是强制关闭。

Open a connection as late as possible. 尽可能晚打开连接。 Close it as soon as possible. 尽快关闭它。 Close it in a "finally" block to make sure it gets closed. 在“最终”块中将其关闭,以确保将其关闭。

And in general, dispose of resources in the reverse order that you obtain them. 通常,以相反的顺序处理资源。

You are basically bloating your application by having an extra cursor open. 您基本上是通过打开一个额外的游标来膨胀您的应用程序。 Best practice is to close the connection. 最佳做法是关闭连接。

I have noticed that there are a lot of exceptions thrown if you dont do it. 我注意到,如果您不这样做,就会抛出很多异常。

If you don't close the database connections, they'll cause memory leaks over time. 如果不关闭数据库连接,它们将随着时间的流逝而导致内存泄漏。 you can use startManagingCursor but along with this you have to close the db connection. 您可以使用startManagingCursor,但与此同时必须关闭数据库连接。 by the way what type of error or exception you are getting while closing db connection in onStop() or onDestroy() method 顺便说一下,在onStop()或onDestroy()方法中关闭数据库连接时遇到的错误或异常类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM