Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new column to Sqlite database table which does not exist in android?

Tags:

android

sqlite

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.

like image 740
Jagadeesh Avatar asked Mar 23 '23 02:03

Jagadeesh


2 Answers

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)

like image 129
Matt Avatar answered Apr 06 '23 04:04

Matt


@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");
     }
    }
}
like image 38
Sunny Avatar answered Apr 06 '23 06:04

Sunny