SQLite add column, keep data

后端 未结 4 810
眼角桃花
眼角桃花 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.

    0 讨论(0)
  • 2021-01-31 10:08

    I have not worked with android, but sqlite provides 'alter table' as most SQL implementations does:

    SQLite alter table

    0 讨论(0)
  • 2021-01-31 10:11

    Please see this page for the syntax to create a new column on a table. Basically it is:

    ALTER TABLE mytable ADD COLUMN mycolumn TEXT
    

    In your onUpgrade method, it would look something like this:

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String upgradeQuery = "ALTER TABLE mytable ADD COLUMN mycolumn TEXT";
        if (oldVersion == 1 && newVersion == 2)
             db.execSQL(upgradeQuery);
    }
    
    0 讨论(0)
  • 2021-01-31 10:13

    A better approach

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        switch (oldVersion) {
            case 1:
                db.execSQL(SQL_MY_TABLE);
    
    
            case 2:
                db.execSQL("ALTER TABLE myTable ADD COLUMN myNewColumn TEXT");
    
        }
    }
    

    Lets say in case 1, you upgraded to db version 2. You created a new table but forgot the myNewColumn you will see in case 2. What this will do is if you change the db version to 3, case 2 will get ran if its upgrading from 2 to 3.

    0 讨论(0)
提交回复
热议问题