Green Dao onUpdate. How can I add new columns to old tables?

柔情痞子 提交于 2019-12-11 14:37:32

问题


When using green dao there is some code customisation needed for updating from one schema to the next. For my earlier needs it was sufficient to add any new tables using code like this in DaoMaster.java:

 if(oldVersion==SCHEMA_VERSION_OLD_VERSION&& newVersion==SCHEMA_VERSION){
             Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by adding language & checklist table");                 
             boolean ifNotExists = true;
             NewTableDao.createTable(db, ifNotExists);
             NewTable2Dao.createTable(db, ifNotExists);              
        }

And so far it's worked great. However for my current schema I have added more connections between the tables, and after updating from the old version, I get crashes indicating that the new columns don't exist.

Is there a way in greendao to add new columns? do I need to write the sqlite code in a old school fashion to get this going? (Any code samples are A LOT of welcome)

Thanks in advance


回答1:


  1. Have a look at the SQL code for creating your table (located in the DAO-class).
  2. Extract the relevant change in the SQL.
  3. Update your exiting table manually.

Example:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.i(TAG, "Update Schema to version: "+Integer.toString(oldVersion)+"->"+Integer.toString(newVersion));
    switch (oldVersion) {
        case 1:
            /* v1->v2: all changes made in version 2 come here */
            db.execSQL("ALTER TABLE "+MyDao.TABLENAME+" ADD COLUMN 'NEW_COL_1' INTEGER;");
            db.execSQL("DROP TABLE IF EXISTS 'MY_OLD_ENTITY'");
            /* break was omitted by purpose. */
        case 2:
            /* v2->v3: all changes made in version 3 come here */
            MyNewDao.createTable(db, true);
            db.execSQL("ALTER TABLE "+MyDao.TABLENAME+" ADD COLUMN 'NEW_COL_2' TEXT;");
            /* break was omitted by purpose. */
    }
}


来源:https://stackoverflow.com/questions/24515967/green-dao-onupdate-how-can-i-add-new-columns-to-old-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!