To add a new column to the table, you need to use ALTER
. In android, you can add a new column inside onUpgrade()
.
You might be wondering how onUpgrade()
will add a new column?
When implementing a subclass of SQLiteOpenHelper
you need to call the constructor of the superclass: super(context, DB_NAME, null, 1);
in your class constructor. There I went 1
for the version.
When I changed version 1
to higher ( 2
or more), onUpgrade()
called. And do the SQL modifications that I intend to do. My class constructor after version change:
public DatabaseHelper(Context context) { super(context, DB_NAME, null, 2);
SQL modifications are checked as follows: the superclass constructor compares the version of the stored SQLite db file with the version that I passed super()
. If these (previous and now) version numbers are different, onUpgrade()
is called.
The 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"); } }
Blasanka Jul 19 '17 at 13:23 2017-07-19 13:23
source share