2

I wanted to add a new column to an Android SQLite Database and then I recieved errors. What should I do and how? I thought that I have to delete the table and create a new one but i don't know how.

2
  • 2
    What have you tried? Can you give some code of what you have and what you want to do? Sep 7, 2011 at 15:05
  • I want to add a new String column, and then I want to verify if the string in that column matches the string on a button.
    – Alex
    Sep 7, 2011 at 15:42

3 Answers 3

5

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 column
    if (newVersion > oldVersion) {
        db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
    }
}

Obviously, the SQL will differ depending on the column definition.

4
  • I should try this for a string column? db.execSQL("ALTER TABLE foo ADD COLUMN answer TEXT NOT NULL");
    – Alex
    Sep 7, 2011 at 15:43
  • The onUpgrade() method is called automatically or i have to call it?
    – Alex
    Sep 7, 2011 at 16:35
  • @Alex It is called automatically by the object when the database is first accessed. When you create SQLiteOpenHelper, one of the args to the constructor is the database version. If the version number in the database is less than the new version supplied in the constructor, onUpgrade() will be called. Sep 7, 2011 at 16:38
  • Now I understand what's happening. The SQLiteOpenHelper calss is called only if I increment the database version. Thank you a lot!!! It works now.
    – Alex
    Sep 7, 2011 at 16:48
0
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");
    }
}
0
0

The right way to add new column to DB, for example in version 2, would be:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 2) {
         db.execSQL("ALTER TABLE table_name ADD COLUMN new_column_name TEXT");
    }
}

It covers all pitfalls, including major issue: if a user goes from version 1 to 3 they will miss the upgrade query completely! These users will be in an awkward limbo where they are missing a few of the intermediate updates and do not have the expected sql schema.

Also don't forget to alter the create statement adding new column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.