在我的应用程序中升级 sqlite 数据库

upgrade sqlite database in my app

那么,我的应用程序已经在 Playstore 上了....

现在,我想在我的应用程序中向数据库添加一列。为此,我必须升级我的数据库,这可以通过更改数据库版本来完成。

用户已经在数据库中有一些东西,当我上传我的应用程序的更新版本(数据库版本更改)时,它会创建一个新的数据库,用户将丢失所有东西 he/she 在 his/her 数据库中。

这个问题的解决方案是什么?以及如何将旧数据库的内容备份/恢复到新数据库? (我知道如何通过简单地以编程方式将数据库复制粘贴到外部存储来备份数据库)。

您可以使用onUpgrade()方法来处理这个问题。

像这样:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     if (oldVersion == 1 && newVersion == 2) {
      db.execSQL("create temporary table people_tmp ("
          + "id integer, name text, position text, posid integer);");

      db.execSQL("insert into people_tmp select id, name, position, posid from people;");
      db.execSQL("drop table people;");

      db.execSQL("create table people ("
          + "id integer primary key autoincrement,"
          + "name text, posid integer);");

      db.execSQL("insert into people select id, name, posid from people_tmp;");
      db.execSQL("drop table people_tmp;");
    }

}

所以。您正在创建临时 table 并将所有需要的信息保存在 table 中。接下来你删除你的 table,创建一个新的并从你的临时 table 中插入值。您可以添加额外的字段,并随意添加您想要的所有内容。

更新: 经过一番谷歌搜索后,我找到了一个更简单的解决方案:

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

 // If you need to add a column
 if (newVersion == 2) {
     db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
 }
}

Alter table 方法将在不丢失数据的情况下更改您的数据库结构。

如果您只是添加一个新列,您可以更改现有的 table 而不是创建新的 table。一个例子:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if(oldVersion<2){
        db.execSQL("ALTER TABLE "+this.getTableName()+" ADD COLUMN "+COLUMNS.NAME+ " integer default 0;", null);
        db.execSQL("UPDATE "+this.getTableName()+ " SET "+COLUMNS.NAME+ "="+COLUMNS.NAMEVALUE+";", null);
    }
};

这里是 Android 关于 onUpgrade() 中 ALTER TABLE 用例的文档。所以在这种情况下,如果您没有重命名或删除现有的 table,则不需要备份旧的 table.

If you add new columns you can use ALTER TABLE to insert them into a live table.

另见: