简体   繁体   English

更新 SQLite 数据库并防止重置所有数据库

[英]Updating SQLite Database and prevent to reset all database

I've got an SQLite database.我有一个 SQLite 数据库。 I would like to update this database to version 2.0.我想将此数据库更新到 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.但是我的应用程序的主要关键是数据库版本 1.0 中的某些部分数据被用户修改了,我不希望版本 2.0 删除这些数据的情况。 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 :首先将构造函数中的版本更改为2

super(context, DBNAME, null, 2);

Although it's a good practice to use a static variable for the version.虽然最好为版本使用 static 变量。

Then you must use onUpgrade() and write code inside it that inserts the new rows:然后您必须使用onUpgrade()并在其中编写插入新行的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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