问题
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:
- Have a look at the SQL code for creating your table (located in the DAO-class).
- Extract the relevant change in the SQL.
- 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