什么是正确的方法,在Android的升级数据库 [英] What is the correct approach to upgrade Database in Android
问题描述
如果我想保留一些旧数据并迁移到数据库的新版本,什么是onUpgrade方法正确的步骤是什么?
If I want to keep some of the old data and migrate to a new version of database , what is the correct steps in onUpgrade method?
- 在保留旧数据
- 在删除旧表
- 创建新表,并将旧数据
有一个简化版本,或者有更好的办法吗?谢谢!
Is there a simplified version or there is a better way? Thanks!
推荐答案
升级数据库:
在表中添加新的领域
做以下步骤onUpgrade
do below steps in onUpgrade
-
复制临时表旧数据
copy old data in temp table
创建新领域新表
再从临时数据复制到新表
again copy data from temp to new table
降临时表
还的onCreate为新用户创建新表
also create new table in onCreate for new users
样品$ C $下的升级
sample code for on upgrade
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < newVersion) {
if (oldVersion == 3) {
/**
* code is upgrade privious version to letest version
* */
db.beginTransaction();
db.execSQL("ALTER TABLE " + TableConstants.TABLE_Mst.getTableName()
+ " RENAME TO " + TableConstants.TABLE_Mst.getTableName() + "_Obsolete");
db.execSQL(TABLE_CREATE_query_Mst);
db.execSQL("INSERT INTO " + TableConstants.TABLE_Mst.getTableName() + "("
+ "f1, f2, f3) "
+ " SELECT f1, f2, f3 FROM " + TableConstants.TABLE_Mst.getTableName() + "_Obsolete");
db.execSQL("DROP TABLE IF EXISTS "
+ TableConstants.TABLE_Mst.getTableName() + "_Obsolete");
db.setTransactionSuccessful();
db.endTransaction();
db.setVersion(newVersion);
}
}
}
在数据库中添加新表
做下面的步骤
在onUpgrade 1.创建新表
in onUpgrade 1. create new table
在的onCreate 1.创建新表
in onCreate 1. create new table
注:管理你的数据库版本,同样为下一个版本,请与旧版本的工作与否。
Note: manage your database version, same for next version, check with older version its work or not.
这篇关于什么是正确的方法,在Android的升级数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!