Android 在应用程序更新时升级数据库

Android 在应用程序更新时升级数据库,android,sql,database,sqlite,Android,Sql,Database,Sqlite,我有一个数据库,我想在下一次更新我的应用程序时更改该数据库..但我不想丢失数据库(应用程序目录中)中的当前数据..我必须将该数据复制到新数据库并删除旧数据库..我如何才能做到这一点?有没有其他想法让我知道 提前谢谢 这是我当前的数据库代码 public class DbUtils { public static String DB_PATH; private String DB_NAME; File dbDir; private SQLiteDatabase dataBase; public D

我有一个数据库,我想在下一次更新我的应用程序时更改该数据库..但我不想丢失数据库(应用程序目录中)中的当前数据..我必须将该数据复制到新数据库并删除旧数据库..我如何才能做到这一点?有没有其他想法让我知道

提前谢谢

这是我当前的数据库代码

public class DbUtils {
public static String DB_PATH;
private String DB_NAME;
File dbDir;
private SQLiteDatabase dataBase;
public DbUtils(File fileDirectory, String sqliteFileName) {

    this.DB_NAME = sqliteFileName;
    dbDir = fileDirectory;
}

public void createDatabaseIfNotExists(Context context) throws IOException {
    boolean createDb = false;

    File dbFile = new File(dbDir.getAbsolutePath() + "/" + DB_NAME);
    DB_PATH = dbFile.getAbsolutePath();

    if (!dbDir.exists()) {
        dbDir.mkdir();
        createDb = true;
    } else if (!dbFile.exists()) {
        createDb = true;
    } else {
        boolean doUpgrade = false;

        if (doUpgrade) {
            dbFile.delete();
            createDb = true;
        }
    }

    if (createDb) {
        InputStream myInput = context.getAssets().open(DB_NAME);
        OutputStream myOutput = new FileOutputStream(dbFile);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    }
}

public SQLiteDatabase getStaticDb() {
    return dataBase = SQLiteDatabase.openDatabase(DB_PATH, null,
            SQLiteDatabase.OPEN_READWRITE);
}

public void closeDataBase(){
    if(dataBase!=null && dataBase.isOpen()){
        dataBase.close();
    }
}

 }

更常见的解决方案是保留数据库,但尽可能多地对其进行转换以使用新版本的应用程序。这称为“数据库升级”

<>你可能会担心,如果这个过程在升级过程中失败了,你既没有旧的数据库,也没有新的数据库。但是,这可以通过数据库事务来解决。如果整个数据库升级过程发生在一个事务中,则该事务要么失败,什么也不做,以便您可以继续使用应用程序的旧版本,要么成功,您可以使用应用程序的新版本

以下是如何在事务中包装数据库升级:

SQLiteDatabase database = SQLiteDatabase.openDatabase(uri, null, SQLiteDatabase.SQLITE_OPEN_READWRITE);
database.beginTransaction();

// put your database upgrade code here, for example:
database.execSQL("ALTER TABLE MyTable ADD NewColumn int");
database.execSQL("ALTER TABLE AnotherTable ADD AnotherColumn int");

database.endTransaction();
database.setTransactionSuccessful();
当您说:“在下次更新时更改该数据库”时,您是指表架构更改吗?我只是想了解为什么要删除当前数据库。