getWritableDatabase与getReadableDatabase的区别

本文详细解析了Android SQLite数据库中的getReadableDatabase与getWritableDatabase两个方法的区别与联系,通过官方文档与源码分析,解释了两个方法在读写数据库方面的不同行为。

最权威莫过于官方文档和源码,下面分别以这两方面给大家看一下

文档说明

getReadableDatabase

getReadableDatabase
Added in API level 1
SQLiteDatabase getReadableDatabase ()
Create and/or open a database. This will be the same object returned by 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 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.
Like getWritableDatabase(), this method may take a long time to return, so you should not call it from the application main thread, including from ContentProvider.onCreate().
Returns
SQLiteDatabase a database object valid until getWritableDatabase() or close() is called.
Throws
SQLiteException if the database cannot be opened
getWritableDatabase

getReadableDatabase

SQLiteDatabase 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 onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and/or onOpen(SQLiteDatabase) will be called.
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 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.
Database upgrade may take a long time, you should not call this method from the application main thread, including from ContentProvider.onCreate().
Returns
SQLiteDatabase a read/write database object valid until close() is called
Throws
SQLiteException if the database cannot be opened for writing

疑问

既然getWritableDatabase与getReadableDatabase都能返回既能读又能写的Database,
为何有两个方法,岂不是累赘?况且,从方法名字来看,一个是写,一个是读,到底体现在哪里呢?

区别

getWritableDatabase取得的实例是以读写的方式打开数据库,如果打开的数据库磁盘满了,此时只能读不能写,此时调用了getWritableDatabase的实例,那么将会发生错误(异常)
getReadableDatabase取得的实例是先调用getWritableDatabase以读写的方式打开数据库,如果数据库的磁盘满了,此时返回打开失败,继而用getReadableDatabase的实例以只读的方式去打开数据库.

源码分析

 public SQLiteDatabase getWritableDatabase() {
        synchronized (this) {
            return getDatabaseLocked(true);
        }
    }
 public SQLiteDatabase getReadableDatabase(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值