On Version upgrade i want to add a new column to the the sqlite database table which is not exsit in android. if the column is already exists it should not alter the table. In onUpgrade() method i am not droping the table becoz i dont want to lose the data.
I pieced a few comments together to get this:
Cursor cursor = database.rawQuery("SELECT * FROM MY_TABLE", null); // grab cursor for all data
int deleteStateColumnIndex = cursor.getColumnIndex("MISSING_COLUMN"); // see if the column is there
if (deleteStateColumnIndex < 0) {
// missing_column not there - add it
database.execSQL("ALTER TABLE MY_TABLE ADD COLUMN MISSING_COLUMN int null;");
}
This intentionally ignores database version number and purely adds the column if it isn't there already (in my case, the version numbers didn't help me as the numbering had gone wonky when this column was supposed to have been added)
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
if(!ColunmExists) {
db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With