首页 > 解决方案 > 在预填充的数据库上处理 sqlite 数据库升级

问题描述

在 android studio 中发布我的 android 应用程序的新版本后,我遇到了问题。

问题是: 我有一个带有 SQlite 数据库的测验应用程序,其中问题和答案已使用 SQLite 数据库浏览器填充。现在,当我向数据库表添加新问题并创建新的数据库版本时,数据库似乎没有反映在更新的应用程序中。我在网上找到的有关数据库升级的教程仅强调在应用程序启动时创建的数据库。像这样

问题:只有当我在 SQLite 中向已经存在的表中添加新记录时,如何处理数据库升级?

我尝试过的: (1)在 DatabaseOpenHelperOnUpgrade()方法中,我删除了添加新记录的表。

结果:应用程序崩溃的活动开始

(2) 将OnUpdrade()方法留空。

结果:新添加的记录没有反映

额外数据:DatabaseOpenHelper OnCreate() 方法也是空的

代码

@Override
public void onCreate(SQLiteDatabase db) {

}

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

    db.execSQL("drop table if exists "+ DatabaseDescription.LectureNotes.TABLE_NAME);
    db.execSQL("drop table if exists "+ DatabaseDescription.QuestionAnswer.TABLE_NAME);
    db.execSQL("drop table if exists "+ DatabaseDescription.Test.TABLE_NAME);
    db.execSQL("drop table if exists "+ DatabaseDescription.Subjects.TABLE_NAME);
    db.execSQL("drop table if exists "+ DatabaseDescription.Topics.TABLE_NAME);
    db.execSQL("drop table if exists "+ DatabaseDescription.Year.TABLE_NAME);
}

标签: androidandroid-sqlitesqliteopenhelper

解决方案


预填充的数据库只会从 assets 文件夹中复制一次。

要使用新版本的预填充数据库进行更新,您需要打开更新后的数据库的副本,然后如果现有数据库有需要保留的数据(例如已回答),则将相关行或表复制到现有数据库中问题)。

这是执行上述更新数据库的示例。Sqlite-asset-helper 库


推荐阅读