To add a new column to the table you need to use ALTER
. In android you can add the new column inside the onUpgrade()
.
You may be wonder, how onUpgrade()
will add the new column?
When you implementing a subclass of SQLiteOpenHelper
, you need to call superclass constructor: super(context, DB_NAME, null, 1);
in your class constructor. There I have passed 1
for version.
When I changed the version 1
to above(2
or greater), onUpgrade()
will invoked. And perform the SQL modifications which I intend to do.
My class constructor after changed the version:
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 2);//version changed from 1 to 2
}
SQL modifications checks like this, superclass constructor compares the version of the stored SQLite db file with the version that I passed to super()
. If these(previous and now) version numbers are different onUpgrade()
gets invoked.
Code should look like this:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// add new columns to migrate to version 2
if (oldVersion < 2) {
db.execSQL("ALTER TABLE " + TABLE_NAME + "ADD COLUMN school VARCHAR(250)");
}
// add new columns to migrate to version 3
if (oldVersion < 3) {
db.execSQL("ALTER TABLE " + TABLE_NAME + "ADD COLUMN age INTEGER");
}
}