Android:打开和关闭SQLite数据库 [英] Android: opening and closing SQLite database

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

问题描述

我正在开发和android应用程序,其中我经常使用访问本地数据库。这个数据库可以从不同的therads访问,所以我有一个数据库的协调问题。我使用以下 open() close()方法。


$ b b

  public void open(){
mDb = mDbHelper.getWritableDatabase();
}

public void close(){
mDb.close();
}

因此,通常当我需要访问db数据库,然后我执行一些操作,最后我关闭数据库。通常用于此目的的代码如下:

  try {
dbManager.open
//数据库操作
} catch(异常e){
// TODO自动生成的catch块
e.printStackTrace();
} finally {
try {
dbManager.close();
} catch(Exception e){
// TODO自动生成的catch块
e.printStackTrace();
}
}

但是,如果对这段代码使用(假设线程A和线程B)可能发生以下情况:

 一个线程:执行open b B线程:perfroms open()
一个线程:perfroms一些操作
一个线程:执行close()
B线程:尝试执行一些操作但是失败!

所以,唯一的解决方案我可以猜测我执行 open / code>当我的应用程序启动和 close()当我的应用程序停止。我不知道这可以是一个很好的解决方案吗?



实际上, getWritableDatabase()方法(从我的 open ))说:

 确保在不再需要数据库时调用close所以,任何人都可以建议我一个替代解决方案?

h2_lin>解决方案

您可以使用单例实例,基本上可以不关闭数据库(但保持事务关闭)。有一些信息:



Android SQLite DB何时关闭


I'm developing and android application in which I often use access the local database. This database can be accessed from differents therads, so I have a coordination problem for the database. I use the following open() and close() method.

public void open(){ 
    mDb=mDbHelper.getWritableDatabase();
}

public void close(){
        mDb.close();
}

So, usually, when I need to access the db for some operations I open the database, then I perform some operation, and finally I close the database. The code I typically use for this purpose is the following:

    try {
        dbManager.open();
                    // database operation
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        try {
            dbManager.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

But, if for this piece of code is used from differnts threads (supposing thread A and thread B) the following situation may occurs:

A thread: performs open()
B thread: perfroms open()
A thread: perfroms some operation
A thread: performs close()
B thread: try to perform some operation but it fails!

So, the only solution I can guess I to perform open() when my application starts and close() when my application is stopped. I'm not sure that this can be this a good solution?

In effect, the documentation of getWritableDatabase() method (called from my open()) says:

Make sure to call close() when you no longer need the database

So, anyone can suggest me an alternative solution?

解决方案

You can use the singletone instance and gennerally you can do not close database (but keep transaction closed). There is some information:

Android SQLite DB When to Close

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

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