How to update an SQLite Database and NOT lose all existing data?

后端 未结 2 1804
北荒
北荒 2021-02-20 11:36

I\'m adding a table to my app\'s SQLite DB. All my syntax there is fine, not the issue. But I\'m having some trouble getting the new table to be created properly. I added the ne

相关标签:
2条回答
  • 2021-02-20 12:05

    if DB version : 6

    Ex : There is a table with 5 columns
    

    When you upgrade to : 7 ( I am adding 1 new column in the 3 tables)

     1. We need to add the columns when creating a table
    
     2. onUpgrade method:
    
     if (oldVersion < 7) 
     { 
        db.execSQL(DATABASE_ALTER_ADD_PAPER_PAID);
        db.execSQL(DATABASE_ALTER_LAST_UPLOADED);
        db.execSQL(DATABASE_ALTER_PAPER_LABEL); 
     }
    

    Where : "DATABASE_ALTER_ADD_PAPER_PAID" is query.

    EX: public static final String DATABASE_ALTER_ADD_PAPER_PAID = "ALTER TABLE "
                    + TableConstants.MY_PAPERS_TABLE + " ADD COLUMN " + COLUMN_PAPER_PAID + " TEXT;";
    

    After above two operation it will works fine for the fresh install user and app upgrade user

    0 讨论(0)
  • 2021-02-20 12:10

    You can do anything you want in onUpgrade. You can use ALTER to add new columns to your table.

    Worst case, if your schema is completely and entirely different, you'll have to create the new table, populate it using data from the old table, and then delete the old table.

    In any case, onUpgrade was designed to allow for a smooth upgrade without any loss of data. It's just up to you to implement it properly.

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