SQLite add column, keep data

后端 未结 4 811
眼角桃花
眼角桃花 2021-01-31 09:19

I have a database with 4 columns:

@Override
public void onCreate(SQLiteDatabase database) {
        database.execSQL(\"CREATE TABLE \" + DATABASENAME + \" (name          


        
4条回答
  •  梦如初夏
    2021-01-31 10:06

    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 mytable ADD COLUMN mycolumn TEXT");
        }
    }
    

    It covers all pitfalls, including major issue with the selected answer: 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.

提交回复
热议问题