Is the onUpgrade method ever called?

后端 未结 6 851
我寻月下人不归
我寻月下人不归 2020-12-07 20:37

Is the onUpgrade method of SQLiteOpenHelper ever called? If so, when is it called and by what? If it is not called by the developers, then why is it there? What really happe

6条回答
  •  北海茫月
    2020-12-07 21:27

    It is actually called when you call getReadableDatabase or getWritableDatabase.

    Deep dive:

    You pass version number in the constructor of SQLiteOpenHelper which is stored in a variable called mNewVersion. That's it. Nothing happens at this point.

    Everytime you call getReadableDatabase or getWritableDatabase, it will call a method called getDatabaseLocked. This method will get the existing version number of the database and compare it with the mNewVersion.

    1. If the database with the given name doesn't exist it will call onCreate
    2. If the new version is greater than old version it will call onUpgrade.
    3. If the new version is lower than existing version, an exception will be thrown.
    4. If they are equal it will go ahead and open the database.

    What should I write in onCreate and onUpgrade ?

    onCreate should contain the code that creates a schema for the first time.

    You can leave onUpgrade empty first time since it won't be called the first time. When you want to change the table structure at later stage, that code should go in here.

    SQLiteOpenHelper.java(Source code)

    public SQLiteDatabase getWritableDatabase() {
        synchronized (this) {
            return getDatabaseLocked(true);
        }
    }
    
     public SQLiteDatabase getReadableDatabase() {
        synchronized (this) {
            return getDatabaseLocked(false);
        }
    }
    
    private SQLiteDatabase getDatabaseLocked(boolean writable) {
       .
       .
    
         final int version = db.getVersion();
    
            if (version != mNewVersion) {
                if (db.isReadOnly()) {
                    throw new SQLiteException("Can't upgrade read-only database from version " +
                            db.getVersion() + " to " + mNewVersion + ": " + mName);
                }
    
                db.beginTransaction();
                try {
                    if (version == 0) {
                        onCreate(db);
                    } else {
                        if (version > mNewVersion) {
                            onDowngrade(db, version, mNewVersion);
                        } else {
                            onUpgrade(db, version, mNewVersion);
                        }
                    }
                    db.setVersion(mNewVersion);
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }
           }
    
           onOpen(db);
     }
    

提交回复
热议问题