Confusion: How does SQLiteOpenHelper onUpgrade() behave? And together with import of an old database backup?

后端 未结 4 1348
后悔当初
后悔当初 2020-11-30 01:03

let\'s assume I have a database table test_table with 2 columns and a corresponding create script in the SQLiteOpenHelper:

DB_VERSION = 1:
public void onCrea         


        
4条回答
  •  时光说笑
    2020-11-30 01:23

    i suspect you can also create a new table with all the columns you need

    CREATE TABLE new_test_table (COL_A, COL_B, COL_C,COL_D);

    copy the data from the old table to the new

    INSERT INTO new_test_table SELECT * FROM test_table;

    drop the old table DROP TABLE test_table;

    and rename the new table

    ALTER TABLE new_test_table RENAME TO test_table;

    so in short

    public void onUpgrade(SQLiteDatabase db,int OldVersion,int NewVersion){
      db.execSQL("CREATE TABLE new_test_table (COL_A, COL_B, COL_C,COL_D);"+
                 "INSERT INTO new_test_table SELECT * FROM test_table;"+
                 "DROP TABLE test_table;"+
                 "ALTER TABLE new_test_table RENAME TO test_table;");"
        }
    

    that way you don't have to worry about dataloss or incremental changes

提交回复
热议问题