简体   繁体   中英

How can I add multiple table without losing any data or table using onUpgrade()

I have already added a table using onUpgrade() and now I just realised a need to add another table. I want to do this without losing any previous data or tables.

I tried removing everything from the onUpgrade to add a new table but it simply crashed the app. I want to keep all the 3 already existing tables and add a new one

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE "+ TABLE_NAME+  "(Datee DATE, Challan INTEGER PRIMARY KEY,Lr VARCHAR, Than INTEGER, Quality TEXT, Decise DATE, Panna INTEGER, Caustic Date, Party TEXT, Marka Text)");
    db.execSQL("Create table "+ TABLE_NAME2+" (id INTEGER PRIMARY KEY AUTOINCREMENT, challan INTEGER UNIQUE, date DATE, than INTEGER, marka VARCHAR, quality VARCHAR ) ");
}

@Override   
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
    db.execSQL("Drop table if exists "+ TABLE_NAME2 );
    onCreate(db);
    db.execSQL("Create table "+ TABLE_NAME3+" (id INTEGER PRIMARY KEY AUTOINCREMENT, marka VARCHAR, indate DATE, qty INTEGER, outdate DATE, stamp DATE Default CURRENT_DATE ) ");

}

You could utilise the IF NOT EXISTS clause in the table definitions.

As such you could use :-

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE_NAME+  "(Datee DATE, Challan INTEGER PRIMARY KEY,Lr VARCHAR, Than INTEGER, Quality TEXT, Decise DATE, Panna INTEGER, Caustic Date, Party TEXT, Marka Text)");
    db.execSQL("Create table IF NOT EXISTS "+ TABLE_NAME2+" (id INTEGER PRIMARY KEY AUTOINCREMENT, challan INTEGER UNIQUE, date DATE, than INTEGER, marka VARCHAR, quality VARCHAR ) ");
    db.execSQL("Create table IF NOT EXISTS "+ TABLE_NAME3+" (id INTEGER PRIMARY KEY AUTOINCREMENT, marka VARCHAR, indate DATE, qty INTEGER, outdate DATE, stamp DATE Default CURRENT_DATE ) ");
}

@Override   
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    onCreate(db);

}

As such existing tables will not be created as they are not dropped.

If you wanted to cater for more complicated scenarios, such as if the App has already been published then you could utilise the oldVersion and/or newVersion values and have specific routines for each version change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM