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,
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.
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.
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.
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.
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