android - 在android中打开和关闭数据库连接?

标签 android sqlite

我搜索了很多问题,但没有得到正确答案。 在 Activity 生命周期中打开和关闭数据库的最佳方式是什么。 请有人帮我提供正确答案。

提前致谢。

最佳答案

使用单例模式并使用 db=DatabaseHelper.getInstance(context) 进行访问。 它保证在整个应用程序生命周期中只存在一个数据库助手。

public class DatabaseHelper extends SQLiteOpenHelper { 

  private static DatabaseHelper sInstance;

  private static final String DATABASE_NAME = "database_name";
  private static final String DATABASE_TABLE = "table_name";
  private static final int DATABASE_VERSION = 1;

  public static synchronized DatabaseHelper getInstance(Context context) {

    // Use the application context, which will ensure that you 
    // don't accidentally leak an Activity's context.
    if (sInstance == null) {
      sInstance = new DatabaseHelper(context.getApplicationContext());
    }
    return sInstance;
  }

  /**
   * Constructor should be private to prevent direct instantiation.
   * make call to static method "getInstance()" instead.
   */
  private DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }
}

并使用访问:

db=DatabaseHelper.getInstance(this);

如果需要,您还可以在 catch block 中关闭数据库连接。 希望对您有所帮助。

关于android - 在android中打开和关闭数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37562636/

相关文章:

java - 在提交时传递自定义对象

android - 在 fragment/子 fragment 中分配主机监听器的最佳位置在哪里?

SQLite 日期 "is greater than other date"例如 '25/09/2014' 不起作用

SQLite UPSERT 有 2 个约束

nhibernate - 使用 NHibernate 和 Mono.Data.SQLite

c# - 优化 sqlite 插入查询

java - 接收 HTTP 请求的响应

java - 为什么eclipse在java的outline View 中隐藏private成员?

java - 如何将上下文从 AyncTask 传递到 DatabaseHandler

android - 从 Sqlite 设置多个警报