SQLiteOpenHelper中的getWritableDatabase和getReadableDatabase会的区别

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. 两者都是数据库操作,可能存在延迟等待,所以尽量不要在主线程中调用。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.什么是Activity?问的不太多,说点有深度的 四大组件之一,一般的,一个用户交互界面对应一个activit...
    JoonyLee阅读 5,765评论 2 51
  • 【每日拔拔草】:三次思维空性;7/3 1.近期自己身体弱及时常生病来自于我过去伤害生命 2.在安排好的时间会遇到障...
    佩诗阅读 131评论 0 0
  • 这个画面是否熟悉? 十九年前的今天,“The last shot”。 1998年6月15日,NB...
    花小凡凡阅读 373评论 0 1