如何在用户设备上升级数据库?

时间:2015-02-17 12:23:17

标签: android database add upgrade

这是我第一次需要更改我的应用程序的数据库结构(已经在Google Play上发布)。 这是我的数据库类:

public class Database extends SQLiteOpenHelper {
    private static final String DB_NAME = "db";
    private static final int DB_VERSION = 1;

    public Database(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String table = "CREATE TABLE users(";
        table += "_id TEXT PRIMARY KEY,";
        table += "name TEXT NOT NULL,";
        table += "surname TEXT NOT NULL,";
        table += "details TEXT);";

        String table2 = "CREATE TABLE favorite(";
        table2 += "id TEXT PRIMARY KEY);";

        String table3 = "CREATE TABLE documents(";
        table3 += "id TEXT PRIMARY KEY,";
        table3 += "text TEXT NOT NULL,";
        table3 += "username TEXT REFERENCES users(_id));";

        String table4 = "CREATE TABLE average(";
        table4 += "user TEXT PRIMARY KEY,";
        table4 += "document INTEGER NOT NULL,";
        table4 += "avg REAL NOT NULL);";

        db.execSQL(table);
        db.execSQL(table2);
        db.execSQL(table3);
        db.execSQL(table4);
    }

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

我添加了下表:

String table5 = "CREATE TABLE categories(";
table5 += "source TEXT PRIMARY KEY,";
table5 += "parent TEXT,";
table5 += "sub TEXT NOT NULL);";

然后添加:

db.execSQL(table5);

现在,我要在onUpgrade方法中添加什么来让用户在他们的设备上拥有更新的数据库? 对不起,如果这可能是一个愚蠢的问题,但我不确定能够做到这一点,我想让用户在新版本的应用程序中获得正确的结构感到安全。

1 个答案:

答案 0 :(得分:0)

当数据库退出并且版本号低于构造函数中的请求时,将调用

onUpgrade()。该方法将表模式更新为请求的版本。

您可以在此处找到更多信息:“When is SQLiteOpenHelper onCreate() / onUpgrade() run?