本文介绍了关闭数据库连接最好的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找对我的问题的答案一段时间,但我didn`t得到我所需要的。我有一个ListView的应用程序,并形成在那里我可以添加新的记录到数据库中。所以没有太多的查询做

I was looking for a while for answer on my question but I didn`t get what I need. I have an application with a ListView, and form where I can add new record to DB. So there is not much queries to do.

如何处理连接到数据库?我应该得到什么,我想还是应该把它打开全部的时间,直到应用程序被关闭后,关闭它?我想知道什么是一边想着性能自动和电池寿命的最佳方式。

How to handle connections to db ? Should I close it after getting what I want or should I keep it open whole time until app is closed ? I want to know what is the best way while thinking about performence and battery life.

推荐答案

根据这篇文章由谷歌工程师,有什么不妥留下数据库连接打开:

According to this post by a Google engineer, there's nothing wrong with leaving the database connection open:

Android的做了一个深思熟虑的设计决策是可以令人惊讶,  只是放弃了对应用程序干净退出的整体思路和  而不是让内核清理自己的资源。毕竟,  内核需要能够反正做到这一点。由于设计,保持  什么的开放进程的生命的整个过程,从来没有关闭它根本就不是一个泄漏。它将被清理时  过程被清除。

所以,为了简单起见,我将扩展应用程序类,以提供一个良好定义的入口点code,然后打开它的的onCreate()。存储数据库连接在你的应用程序领域,并提供一个访问方法提供给你的code其余部分的连接。

So, for simplicity, I would extend the Application class to provide a single well-defined entry point for your code, and open the database connection in its onCreate(). Store the DB connection as a field in your Application, and provide an accessor method to make the connection available to rest of your code.

那么,不用担心其关闭。

Then, don't worry about closing it.

这篇关于关闭数据库连接最好的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:59
查看更多