Android中的数据库访问 [英] Database Access in Android

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

问题描述

我正在创建一个Android应用程序,它基本上是关于Mushrooms的信息列表。我从sqlite数据库中获取此信息。我有一个全局单例,里面有一个服务类,我用它来访问我的数据库。几乎每个活动都访问数据库。是否最好让我的数据库一直打开,或者在我需要数据时打开和关闭它?

I am creating an android app that is basically a listing of information on Mushrooms. I get this information from an sqlite database. I have a global singleton with a services class inside it in which I use to access my db. Almost every activity accesses the db. Is it better to leave my db open all the time or open and close it as I need the data?

如果最佳做法是始终保持打开状态,如果我在活动被销毁时将其打开,我需要在哪里确保关闭它以及最糟糕的情况是什么?

If the best practice is to leave it open all the time, where do I need to make sure to close it and what is the worst case scenario if I left it open when the activity was destroyed?

推荐答案

根据我过去的Java经验,我会说最好关闭连接,它可能在一个小型的Android应用程序中无关紧要,但如果你有10个应用程序正在运行并且所有应用程序都访问数据库,那么你有10个挂起的连接。再开始一些,迟早另一个应用程序将不得不等待,因为SQL服务器无法处理更多的请求。

Based on my past experience in Java I would say it is better to close the connection, it probably doesn't matter in a small Android application, but if you have 10 applications running and all of them access the database, you have 10 pending connections. Start a few more and sooner or later another application will have to wait because the SQL server can't handle any more requests.

我想你可以把它想象成一个您的计算机上的文件。您从中读取数据,然后在完成后关闭它。为什么要在你的应用程序中打开一个文件?

I guess you could think of it as a file on your computer. You read data from it, and then close it when your done. Why keep a file open in your application?

现在我对Android编程很新,所以我还没有实现数据库调用。但是几年前,当我在Java应用程序中遇到同样的问题时,我实现了一个数据库对象,我在其中连接到数据库。 其他人(类)必须调用数据库对象(单例或最终方法)来获取数据,有点像存储过程,而不是在应用程序中。

Now I'm very new to Android programming so I haven't got around to implement database calls. But when I faced the same problem in a Java application a few years ago I implemented a database object, in which I had the connection to the database. "Everyone else" (the classes) had to call the database object (singleton or final methods) to get data, sort of like stored procedures but in the application instead.

因此,我知道何时拨打电话以及何时停止。然后我进入超时状态,好像几分钟内什么也没发生,我会关闭与数据库的连接。 (这也处理了一些超时异常,因为连接的超时永远不会发生。)当输入新的呼叫时,我可以轻松地启动新连接并使用新的数据库连接。

Because of this I knew when the calls where made and when they stopped. I then put in a timeout, so as if nothing happened in a few minutes, I would close the connection to the db. (This also took care of some timeout exceptions because the timeout of the connection would never happen.) When a new call entered, I could easily start a new connection and use the new db connection.

基本上我通过将方法设为 public Fungus [] getAllFungus() public Fungus [] getFilteredFungus(string where)来抽象出SQL调用)

Basically I abstracted away SQL calls by having methods as public Fungus[] getAllFungus() and public Fungus[] getFilteredFungus(string where).

这篇关于Android中的数据库访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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