Is the onUpgrade method ever called?

后端 未结 6 863
我寻月下人不归
我寻月下人不归 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:34

    For those of you who would like to know the exact moment when onUpgrade() gets called, it is during a call to either getReadableDatabase() or getWriteableDatabase().

    To those who are not clear how it ensure it gets triggered, the answer is: It is triggered when the database version provided to the constructor of SqLiteOpenHelper is updated. Here is a example

    public class dbSchemaHelper extends SQLiteOpenHelper {
    
    private String sql;
    private final String D_TAG = "FundExpense";
    //update this to get onUpgrade() method of sqliteopenhelper class called
    static final int DB_VERSION = 2; 
    static final String DB_NAME = "fundExpenseManager";
    
    public dbSchemaHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        // TODO Auto-generated constructor stub
    }
    

    now to...onUpgrade()

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        sql = "ALTER TABLE " + fundExpenseSchema.Expense.TABLE_NAME + " ADD COLUMN " + fundExpenseSchema.Expense.FUNDID + " INTEGER";
        arg0.execSQL(sql);
    }
    

提交回复
热议问题