How to add new Column to Android SQLite Database?
Perhaps a slightly more elegant approach using switch instead of if/then that will upgrade from any schema to the most recent schema...
Here's also a decent page on the syntax for altering a table: http://alvinalexander.com/android/sqlite-alter-table-syntax-examples
public static final String TABLE_TEAM = "team";
public static final String COLUMN_COACH = "coach";
public static final String COLUMN_STADIUM = "stadium";
private static final String DATABASE_ALTER_TEAM_TO_V2 = "ALTER TABLE "
+ TABLE_TEAM + " ADD COLUMN " + COLUMN_COACH + " TEXT;";
private static final String DATABASE_ALTER_TEAM_TO_V3 = "ALTER TABLE "
+ TABLE_TEAM + " ADD COLUMN " + COLUMN_STADIUM + " TEXT;";
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion)
{
case 1:
//upgrade from version 1 to 2
db.execSQL(DATABASE_ALTER_TEAM_TO_V2);
case 2:
//upgrade from version 2 to 3
db.execSQL(DATABASE_ALTER_TEAM_TO_V3);
//and so on.. do not add breaks so that switch will
//start at oldVersion, and run straight through to the latest
}
}
you can use ALTER TABLE
function on your onUpgrade()
method, like this:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
}
}
Obviously, the SQLite will differ depending on the column definition.
The easiest way to do this is to add some SQL to the onUpgrade()
method in your SQLiteOpenHelper class
. Something like:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a new column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE student ADD COLUMN student_rollno INTEGER DEFAULT 0");
}
}
I came across this thread when needing help on my own app, but saw issues with many of the answers. I would recommend doing the following:
private static final String DATABASE_ALTER_TEAM_1 = "ALTER TABLE "
+ TABLE_TEAM + " ADD COLUMN " + COLUMN_COACH + " string;";
private static final String DATABASE_ALTER_TEAM_2 = "ALTER TABLE "
+ TABLE_TEAM + " ADD COLUMN " + COLUMN_STADIUM + " string;";
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
db.execSQL(DATABASE_ALTER_TEAM_1);
}
if (oldVersion < 3) {
db.execSQL(DATABASE_ALTER_TEAM_2);
}
}
You want to make sure the code will work when users upgrade more than 1 version and that the update statement only runs the one upgrade it is needed. For a bit more on this, check out this blog.