SQLite 數(shù)據(jù)庫打開異常時(shí)刪除DB文件

SQLite 在打開DB文件時(shí)铣鹏,如果遇到打不開的情況讽膏,會(huì)刪除DB 文件镐侯,有點(diǎn)兇殘欠窒。

我們來查看源碼

  • 1伪嫁、android.database.sqlite.SQLiteDatabase
private SQLiteDatabase(String path, int openFlags, CursorFactory cursorFactory,
        DatabaseErrorHandler errorHandler) {
    mCursorFactory = cursorFactory;
    mErrorHandler = errorHandler != null ? errorHandler : new DefaultDatabaseErrorHandler();
    mConfigurationLocked = new SQLiteDatabaseConfiguration(path, openFlags);
}

我們需要看一下SQLite 在Database 出錯(cuò)時(shí)候的處理 弯汰,打開 DefaultDatabaseErrorHandler

  • 2序调、android.database.DefaultDatabaseErrorHandler
public final class DefaultDatabaseErrorHandler implements DatabaseErrorHandler {

    private static final String TAG = "DefaultDatabaseErrorHandler";

    /**
     * defines the default method to be invoked when database corruption is detected.
     * @param dbObj the {@link SQLiteDatabase} object representing the database on which corruption
     * is detected.
     */
    public void onCorruption(SQLiteDatabase dbObj) {
        Log.e(TAG, "Corruption reported by sqlite on database: " + dbObj.getPath());

        // is the corruption detected even before database could be 'opened'?
        if (!dbObj.isOpen()) {
            // database files are not even openable. delete this database file.
            // NOTE if the database has attached databases, then any of them could be corrupt.
            // and not deleting all of them could cause corrupted database file to remain and 
            // make the application crash on database open operation. To avoid this problem,
            // the application should provide its own {@link DatabaseErrorHandler} impl class
            // to delete ALL files of the database (including the attached databases).
            deleteDatabaseFile(dbObj.getPath());
            return;
        }

        List<Pair<String, String>> attachedDbs = null;
        try {
            // Close the database, which will cause subsequent operations to fail.
            // before that, get the attached database list first.
            try {
                attachedDbs = dbObj.getAttachedDbs();
            } catch (SQLiteException e) {
                /* ignore */
            }
            try {
                dbObj.close();
            } catch (SQLiteException e) {
                /* ignore */
            }
        } finally {
            // Delete all files of this corrupt database and/or attached databases
            if (attachedDbs != null) {
                for (Pair<String, String> p : attachedDbs) {
                    deleteDatabaseFile(p.second);
                }
            } else {
                // attachedDbs = null is possible when the database is so corrupt that even
                // "PRAGMA database_list;" also fails. delete the main database file
                deleteDatabaseFile(dbObj.getPath());
            }
        }
    }

    private void deleteDatabaseFile(String fileName) {
        if (fileName.equalsIgnoreCase(":memory:") || fileName.trim().length() == 0) {
            return;
        }
        Log.e(TAG, "deleting the database file: " + fileName);
        try {
            SQLiteDatabase.deleteDatabase(new File(fileName));
        } catch (Exception e) {
            /* print warning and ignore exception */
            Log.w(TAG, "delete failed: " + e.getMessage());
        }
    }
}

我們可以看到 DefaultDatabaseErrorHandler 的處理方式与纽,如果這個(gè)數(shù)據(jù)庫打不開就會(huì)刪除這個(gè)DB文件堰怨,如果當(dāng)前DB 有 attach 其他數(shù)據(jù)庫的話芥玉,也有可能會(huì)被刪除,所以開發(fā)者應(yīng)該提供自己的DatabaseErrorHandler

  • 3备图、SQLiteOpenHelper

我們通過繼承SQLiteOpenHelper 來使用SQLite 數(shù)據(jù)庫 【詳見:SQLite學(xué)習(xí)一灿巧、基礎(chǔ)使用】;
我們提供自己的DatabaseErrorHandler

public class WyhcjgOpenHelper extends SQLiteOpenHelper {

public WyhcjgOpenHelper(Context context, String path) {
    super(context, path, null, VERSION, null, new DatabaseErrorHandler() {
        @Override
        public void onCorruption(SQLiteDatabase sqLiteDatabase) {
            Logger.t(TAG).i("WyhcjgOpenHelper sqlite onCorruption " + sqLiteDatabase.getPath());
        }
    });
    this.mContext = context;
}
}

使用sqlcipher 時(shí)的修改

  • 1揽涮、net.sqlcipher.database.SQLiteDatabase
...
public static SQLiteDatabase openOrCreateDatabase(File file, String password, SQLiteDatabase.CursorFactory factory, SQLiteDatabaseHook databaseHook, DatabaseErrorHandler errorHandler) {
    return openOrCreateDatabase(file == null?null:file.getPath(), password, factory, databaseHook, errorHandler);
}
...
  • 2抠藕、net.sqlcipher.DefaultDatabaseErrorHandler
public void onCorruption(SQLiteDatabase dbObj) {
    Log.e(this.TAG, "Corruption reported by sqlite on database, deleting: " + dbObj.getPath());
    if(dbObj.isOpen()) {
        Log.e(this.TAG, "Database object for corrupted database is already open, closing");

        try {
            dbObj.close();
        } catch (Exception var3) {
            Log.e(this.TAG, "Exception closing Database object for corrupted database, ignored", var3);
        }
    }

    this.deleteDatabaseFile(dbObj.getPath());
}

同樣的,如果這個(gè)數(shù)據(jù)庫打不開就會(huì)刪除這個(gè)DB文件绞吁。

  • 3幢痘、net.sqlcipher.database.SQLiteOpenHelper
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version, SQLiteDatabaseHook hook, DatabaseErrorHandler errorHandler) {
    this.mDatabase = null;
    this.mIsInitializing = false;
    if(version < 1) {
        throw new IllegalArgumentException("Version must be >= 1, was " + version);
    } else if(errorHandler == null) {
        throw new IllegalArgumentException("DatabaseErrorHandler param value can't be null.");
    } else {
        this.mContext = context;
        this.mName = name;
        this.mFactory = factory;
        this.mNewVersion = version;
        this.mHook = hook;
        this.mErrorHandler = errorHandler;
    }
}
  • 4、SQLiteOpenHelper

我們通過繼承SQLiteOpenHelper 來使用SQLite 數(shù)據(jù)庫 【詳見:SQLite學(xué)習(xí)一家破、基礎(chǔ)使用】颜说;
我們提供自己的DatabaseErrorHandler

public class WyhcjgOpenHelper extends SQLiteOpenHelper {

public WyhcjgOpenHelper(Context context, String path) {
    super(context, path, null, VERSION, null, new DatabaseErrorHandler() {
        @Override
        public void onCorruption(SQLiteDatabase sqLiteDatabase) {
            Logger.t(TAG).i("WyhcjgOpenHelper sqlite onCorruption " + sqLiteDatabase.getPath());
        }
    });
    this.mContext = context;
}
}

使用Room 時(shí)的修改

  • 獲取 *Database 的實(shí)例時(shí)
TaskDatabase extends RoomDatabase
...
public synchronized static TaskDatabase getInstance(byte[] passphrase) {
    if (INSTANCE == null) {
        synchronized (TaskDatabase.class) {
            if (INSTANCE == null) {
                INSTANCE = Room
                        .databaseBuilder(mContext.getApplicationContext(), TaskDatabase.class, sDbPath)
                        .openHelperFactory(new HelperFactory(passphrase))
                        .allowMainThreadQueries()
                        .addMigrations(migration_1_2)
                        .build();
            }

        }
    }
    return (INSTANCE);
}
  • new HelperFactory(passphrase)
public class HelperFactory implements SupportSQLiteOpenHelper.Factory {

    private byte[] passphrase;

    public HelperFactory(byte[] passphrase) {
        this.passphrase = passphrase;
    }

    @Override
    public SupportSQLiteOpenHelper create(SupportSQLiteOpenHelper.Configuration configuration) {
        return (new Helper(configuration.context, configuration.name, configuration.callback, passphrase));
    }
}
  • android.arch.persistence.db.framework.Helper
OpenHelper(Context context, String name, final Database[] dbRef,
           final Callback callback, byte[] passphrase) {
    super(context, name, passphrase, CIPHER_SPEC, null, callback.version,
            new DatabaseErrorHandler() {

                @Override
                public void onCorruption(SQLiteDatabase dbObj) {
                    /*Database db = dbRef[0];
                    if (db != null) {
                        callback.onCorruption(db);
                    }*/
                }
            });
    mCallback = callback;
    mDbRef = dbRef;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末购岗,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子门粪,更是在濱河造成了極大的恐慌喊积,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,183評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件玄妈,死亡現(xiàn)場(chǎng)離奇詭異乾吻,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)拟蜻,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門绎签,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人酝锅,你說我怎么就攤上這事诡必。” “怎么了搔扁?”我有些...
    開封第一講書人閱讀 168,766評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵爸舒,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我稿蹲,道長(zhǎng)扭勉,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,854評(píng)論 1 299
  • 正文 為了忘掉前任苛聘,我火速辦了婚禮涂炎,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘焰盗。我一直安慰自己璧尸,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評(píng)論 6 398
  • 文/花漫 我一把揭開白布熬拒。 她就那樣靜靜地躺著爷光,像睡著了一般。 火紅的嫁衣襯著肌膚如雪澎粟。 梳的紋絲不亂的頭發(fā)上蛀序,一...
    開封第一講書人閱讀 52,457評(píng)論 1 311
  • 那天,我揣著相機(jī)與錄音活烙,去河邊找鬼徐裸。 笑死,一個(gè)胖子當(dāng)著我的面吹牛啸盏,可吹牛的內(nèi)容都是我干的重贺。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼气笙!你這毒婦竟也來了次企?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,914評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤潜圃,失蹤者是張志新(化名)和其女友劉穎缸棵,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體谭期,經(jīng)...
    沈念sama閱讀 46,465評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡堵第,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了隧出。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片踏志。...
    茶點(diǎn)故事閱讀 40,675評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖胀瞪,靈堂內(nèi)的尸體忽然破棺而出狰贯,到底是詐尸還是另有隱情,我是刑警寧澤赏廓,帶...
    沈念sama閱讀 36,354評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站傍妒,受9級(jí)特大地震影響幔摸,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜颤练,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評(píng)論 3 335
  • 文/蒙蒙 一既忆、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧嗦玖,春花似錦患雇、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至器瘪,卻和暖如春翠储,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背橡疼。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評(píng)論 1 274
  • 我被黑心中介騙來泰國打工援所, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人欣除。 一個(gè)月前我還...
    沈念sama閱讀 49,091評(píng)論 3 378
  • 正文 我出身青樓住拭,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子滔岳,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評(píng)論 2 360

推薦閱讀更多精彩內(nèi)容