【问题标题】:open and close database Connection in android?在android中打开和关闭数据库连接?
【发布时间】:2016-06-01 07:53:00
【问题描述】:

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

提前致谢。

【问题讨论】:

标签: android sqlite


【解决方案1】:

使用单例模式并使用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 块中关闭数据库连接。 希望对你有帮助。

【讨论】:

  • 虽然这个答案很好,但请为用户when 解释应该打开和关闭连接。据我所知,用户希望在应用程序期间使用数据库,并希望知道何时开始连接以及何时结束连接。例如,数据库应该在 "MainActivity".onCreate() 中打开,并在 "MainActivity".onDestroy 中关闭,这样,数据库可以在整个堆栈中使用,同时在单点进行管理。否则,它也可以在 ApplicationContext 中完成,但关闭会更难(不知道应用程序)
  • 是的,正确的用户可以在 onCreate() 中打开并在使用后或在 onStop 中关闭。但请检查此答案stackoverflow.com/a/7739454/5275436。根据这篇文章,打开数据库连接没有任何问题。所以它是在应用程序中处理单个数据库实例的更好方法。
【解决方案2】:

你可以这样打开数据库

public void openDataBase() throws SQLException {
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
        }

关闭数据库

 public synchronized void close() {
        if (myDataBase != null)
            myDataBase.close();
        //you need to extend the class with SQLiteOpenHelper
         super.close();
    }

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 2017-02-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多