简体   繁体   中英

Updating SQLite Database and prevent to reset all database

I've got an SQLite database. I would like to update this database to version 2.0. But the main key of my app is that some parts of data from database version 1.0 are modified by users and I don't want the situation that version 2.0 erase this data. What I want is to add some rows to database and prevent reset all databases. How can I do it?

public static final String DBNAME = "Animals.db";

@SuppressLint("SdCardPath")

public static final String DBLOCATION = "/data/data/com.erk.animals/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;





public DatabaseHelper(Context context) {

    super(context, DBNAME, null, 1);
    this.mContext = context;
}


@Override
public void onCreate(SQLiteDatabase db) {


}

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

}


public void openDatabase() {

    String dbPath = mContext.getDatabasePath(DBNAME).getPath();
    if (mDatabase != null && mDatabase.isOpen()) {
        return;
    }
    mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}

public void closeDatabase() {

    if (mDatabase != null) {
        mDatabase.close();
    }

}

First change the version inside the constructor to 2 :

super(context, DBNAME, null, 2);

Although it's a good practice to use a static variable for the version.

Then you must use onUpgrade() and write code inside it that inserts the new rows:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 2) {  // or if (oldVersion == 1)
        // write code here
    }
}

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