SQLiteOpenHelper中的getWritableDatabase和getReadableDatabase會的區別

weixin_34249678發表於2016-04-19

1. 兩個方法幹嘛的?

兩個方法都是用於獲取資料庫的讀寫物件,並不是字面上一個獲取讀取資料庫的物件,另一個獲取寫資料庫的物件。

2. getWritableDatabase()

原始碼註釋:

/**
* Create and/or open a database that will be used for reading and writing.
* The first time this is called, the database will be opened and
* {@link #onCreate}, {@link #onUpgrade} and/or {@link #onOpen} will be
* called.
*
* <p>Once opened successfully, the database is cached, so you can
* call this method every time you need to write to the database.
* (Make sure to call {@link #close} when you no longer need the database.)
* Errors such as bad permissions or a full disk may cause this method
* to fail, but future attempts may succeed if the problem is fixed.</p>
*
* <p class="caution">Database upgrade may take a long time, you
* should not call this method from the application main thread, including
* from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
*
* @throws SQLiteException if the database cannot be opened for writing
* @return a read/write database object valid until {@link #close} is called
*/
public synchronized SQLiteDatabase getWritableDatabase();
  • 它會呼叫並返回一個可以讀寫資料庫的物件
  • 在第一次呼叫時會呼叫onCreate的方法
  • 當資料庫存在時會呼叫onOpen方法
  • 結束時呼叫onClose方法

3. getReadableDatabase()

原始碼註釋:

/**
* Create and/or open a database.  This will be the same object returned by
* {@link #getWritableDatabase} unless some problem, such as a full disk,
* requires the database to be opened read-only.  In that case, a read-only
* database object will be returned.  If the problem is fixed, a future call
* to {@link #getWritableDatabase} may succeed, in which case the read-only
* database object will be closed and the read/write object will be returned
* in the future.
*
* <p class="caution">Like {@link #getWritableDatabase}, this method may
* take a long time to return, so you should not call it from the
* application main thread, including from
* {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
*
* @throws SQLiteException if the database cannot be opened
* @return a database object valid until {@link #getWritableDatabase}
*     or {@link #close} is called.
*/
  • 它會呼叫並返回一個可以讀寫資料庫的物件
  • 在第一次呼叫時會呼叫onCreate的方法
  • 當資料庫存在時會呼叫onOpen方法
  • 結束時呼叫onClose方法

4. 區別

是不是上面兩個總結一樣?
然後事實呢?

  1. 兩個方法都是返回讀寫資料庫的物件,但是當磁碟已經滿了時,getWritableDatabase會拋異常,而getReadableDatabase不會報錯,它此時不會返回讀寫資料庫的物件,而是僅僅返回一個讀資料庫的物件。
  2. getReadableDatabase會在問題修復後繼續返回一個讀寫的資料庫物件。
  3. 兩者都是資料庫操作,可能存在延遲等待,所以儘量不要在主執行緒中呼叫。

相關文章