Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new Column to Android SQLite Database?

I have one problem with Android SQLite database.

I have one table which contains one field.StudentFname and that application is working fine with Android 2.3.1 and now if I add another field then my application is not working properly.

Can anyone help me who knows database very well,

like image 607
Aamirkhan Avatar asked Nov 28 '11 04:11

Aamirkhan


People also ask

How do I add a new column in SQLite?

Syntax. The syntax to ADD A COLUMN in a table in SQLite (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition; table_name.

How do I add multiple columns in SQLite?

SQLite does not support adding multiple columns to a table using a single statement. To add multiple columns to a table, you must execute multiple ALTER TABLE ADD COLUMN statements.


2 Answers

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.

like image 146
DevYudh Avatar answered Sep 28 '22 08:09

DevYudh


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.

like image 43
PFranchise Avatar answered Sep 28 '22 10:09

PFranchise