我在10M sqlitedb里面有一个4.20版本的android应用程序,现在我有一个4.21版本的应用程序在100M sqlitedb中,我想升级4.20到4.21,当它升级完成后,我发现在4.21应用程序中仍然保持着10米。
因此,问题是如何在升级应用程序4.20 -> 4.21时覆盖sqlitedb。
我的业务是: app将有很多数据同步。为了进行优化,每个应用程序在发布时都会将初始化数据填充到SQLite中。因此,在每个应用程序升级后,我希望完全覆盖SQLite。
任何帮助都是非常可取的。
发布于 2021-03-11 09:50:45
您可以升级您的数据库版本,并在您的onUpgrade()方法中删除所有表,并调用onCreate()方法重新创建数据库。
public class MyOpenHelper extends SQLiteOpenHelper {
...
private void resetDB(SQLiteDatabase db) {
// Drop all tables
db.execSQL("DROP TABLE IF EXISTS table_name");
// TODO duplicate above line for other tables
// Crate tables again
onCreate(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
resetDB(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onDowngrade(db, oldVersion, newVersion);
resetDB(db);
}
}发布于 2021-03-11 10:03:04
问题是没有调用onUpgrade函数,因为当您从资产加载数据库时,默认版本是。
当您调用应该调用db.getReadableDatabase()或db.getWriteableDatabase方法的onUpgrade方法时,它会失败,因为版本号0应该是一个新的数据库。
如果您看到SqliteOpenHelper源代码
db.beginTransaction();
try {
//Skips updating in your case
if (version == 0) {
onCreate(db);
} else {
if (version > mNewVersion) {
onDowngrade(db, version, mNewVersion);
} else {
onUpgrade(db, version, mNewVersion);
}
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}当db的版本号为时,不调用onUpgrade函数。
解决此问题的一种方法是在将db添加到资产或在打开之前更改它时更改db的版本号。
解决方案更改版本号和您的问题。
try
{
String myPath = MyApplication.context.getDatabasePath(DATABASE_NAME).toString();
//open a database directly without Sqliteopenhelper
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
//if the version is default 0 the update the version
if (myDataBase.getVersion() == 0)
{
//update the database version to the previous one
myDataBase.execSQL("PRAGMA user_version = " + 1);
}
//Close DataBase
myDataBase.close();
}
catch (Exception e)
{
//Do Nothing a fresh install happened
}https://stackoverflow.com/questions/66578376
复制相似问题