SQLiteOpenHelper中的getWritableDatabase和getReadableDatabase会的区别

作者:doMyselfzy
链接:https://www.jianshu.com/p/a5a60451e886

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. 两者都是数据库操作,可能存在延迟等待,所以尽量不要在主线程中调用。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值