关闭数据库连接的最佳位置 [英] Best place to close database connection

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

问题描述

我一直在寻找关于我的问题的答案,但我没有得到我需要的东西.我有一个带有 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.

推荐答案

根据 这篇由 Google 工程师 (Dianne Hackborn) 撰写的帖子,保持数据库连接打开没有任何问题:

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

Android 做出了一个看似令人惊讶的深思熟虑的设计决定,只是放弃应用程序干净退出的整个想法,而是让内核清理它们的资源.毕竟,无论如何,内核都需要能够做到这一点.鉴于这种设计,保持任何东西在一个进程的整个生命周期内打开并且从不关闭它根本就不是泄漏.当它被清理时进程被清理.

Android made a deliberate design decision that is can seem surprising, to just give up on the whole idea of applications cleanly exiting and instead let the kernel clean up their resources. After all, the kernel needs to be able to do this anyway. Given that design, keeping anything open for the entire duration of a process's life and never closing it is simply not a leak. It will be cleaned up when the process is cleaned up.

因此,为简单起见,我将扩展 Application 类以为您的代码提供一个明确定义的入口点,并在其 onCreate() 中打开数据库连接.将数据库连接存储为应用程序中的字段,并提供访问器方法以使连接可​​用于其余代码.

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.

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

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