在基类table增加upgrade操作:

public abstract class DbBaseTable {

	private static final String TAG = "DbBaseTable";

	/**
* @return the DB table name
*/
abstract String getName(); /**
* Creates the DB table according to the DB scheme
*
* @param db
*/
abstract void onCreate(SQLiteDatabase db); void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tempName) { //Rename old table to temporary name
<strong>DbUtils.renameTable(db, getName(), tempName);</strong> //Create clear table according to the new scheme
<strong> onCreate(db);</strong>
//Copy content of the matching columns from the old table to the new one
<strong> joinColumns(db, tempName, getName());</strong> //Delete old table
<strong> DbUtils.dropTable(db, tempName);</strong> //这个是更新一些表的内容
initTableContent(db);
} void initTableContent(SQLiteDatabase db) {
} void joinColumns(SQLiteDatabase db, String tempName, String tableName) {
<strong>DbUtils.joinColumns(db, tempName, tableName);</strong>
} }
final class DbUtils {

    private static final String TAG = "DbUtils";
private static final boolean DEBUG = false; private static final String SQLITE_STMT_LIST_TABLES =
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'android%'";
private static final String SQLITE_TABLE_NAME_COLUMN = "name";
private static final String SQLITE_STMT_TEMPLATE_LIST_COLUMNS = "SELECT * FROM %s LIMIT 1";
private static final String SQLITE_STMT_TEMPLATE_DROP_TABLE = "DROP TABLE IF EXISTS %s";
private static final String SQLITE_STMT_TEMPLATE_RENAME_TABLE = "ALTER TABLE %s RENAME TO %s";
private static final String SQLITE_STMT_TEMPLATE_COPY_COLUMNS = "INSERT INTO %s (%s) SELECT %s FROM %s"; /**
* @param db
* @return Collection object containing table names in the database
*/
static Collection<String> listTables(SQLiteDatabase db) { Cursor cursor = db.rawQuery(SQLITE_STMT_LIST_TABLES, null);
if (cursor == null || !cursor.moveToFirst()) { if (cursor != null) {
cursor.close();
}
return null;
} int table_name_column = cursor.getColumnIndex(SQLITE_TABLE_NAME_COLUMN);
HashSet<String> tables = new HashSet<String>(cursor.getCount());
do {
tables.add(cursor.getString(table_name_column));
} while (cursor.moveToNext());
cursor.close(); return tables;
} /**
* @param db
* @param table
* @return List of column names in the DB table
*/
public static List<String> listColumns(SQLiteDatabase db, String table) { Cursor cursor = db.rawQuery(String.format(SQLITE_STMT_TEMPLATE_LIST_COLUMNS, table), null);
if (cursor == null) {
return null;
} List<String> columns = Arrays.asList(cursor.getColumnNames());
cursor.close(); return columns;
} /**
* @param db
* @param table
*/
static void dropTable(SQLiteDatabase db, String table) { db.execSQL(String.format(SQLITE_STMT_TEMPLATE_DROP_TABLE, table));
} static void renameTable(SQLiteDatabase db, String oldName, String newName) { db.execSQL(String.format(SQLITE_STMT_TEMPLATE_RENAME_TABLE, oldName, newName));
} static void joinColumns(SQLiteDatabase db, String oldTable, String newTable) { //Delete all records in the new table before copying from the old table
db.delete(newTable, null, null); //Find columns which exist in both tables
ArrayList<String> old_columns = new ArrayList<String>(listColumns(db, oldTable));
List<String> new_columns = listColumns(db, newTable);
old_columns.retainAll(new_columns); String common_columns = TextUtils.join(",", old_columns); //Copy records from old table to new table example:<span style="font-family: 微软雅黑;"><strong><span style="font-size:10px;">INSERT INTO Mytest1 (_id,account_id,test1,test3) SELECT _id,account_id,test1,test3 FROM Mytest1_temp_</span></strong></span>
db.execSQL(String.format(SQLITE_STMT_TEMPLATE_COPY_COLUMNS, newTable, common_columns, common_columns, oldTable));
} }

然后在DBHelper中重载onUpgrade方法:

 @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //Get table names in the old DB
Collection<String> old_tables = DbUtils.listTables(db);
if (old_tables == null || old_tables.size() == 0) {
onCreate(db);
return;
} //Get table names in the new DB
Set<String> new_tables = DataBaseClass.sRCMDbTables.keySet(); try {
db.beginTransaction();
//Remove old tables which are not in the new DB scheme
HashSet<String> obsolete_tables = new HashSet<String>();
for (String table : old_tables) {
if (!new_tables.contains(table)) {
System.out.println("====DBHelp onUpgrade droptable table="+table);
DbUtils.dropTable(db, table);
obsolete_tables.add(table);
}
}
old_tables.removeAll(obsolete_tables); //Create and upgrade new tables
DbBaseTable table_descriptor;
for (String table : new_tables) {
table_descriptor = DataBaseClass.sRCMDbTables.get(table); //Check if the new table exists in the old DB
if (old_tables.contains(table)) {
String temp_name = getTempTableName(table, old_tables, new_tables);
System.out.println("====DBHelp onUpgrade temp_name ="+temp_name);
table_descriptor.onUpgrade(db, oldVersion, newVersion, temp_name);
} else {
table_descriptor.onCreate(db);
}
}
db.setTransactionSuccessful();
} catch (Throwable e) { throw new RuntimeException("DB upgrade failed: " + e.getMessage());
} finally {
db.endTransaction();
}
}

中心思想是:

对照新旧的database结构,假设旧表中有table新的database里没有,则删除旧表里的

假设新database中有一个table更新。则须要更新这个表的结构。然后把旧表中数据拷贝过来

(把旧表rename一个名字。把命名后的表中的数据复制到新表中)

代码能够在http://download.csdn.net/detail/baidu_nod/7684479下载

版权声明:本文博客原创文章。博客,未经同意,不得转载。

android数据库升级的措辞的更多相关文章

  1. Android数据库升级

    随着Android应用版本的迭代,经常遇到数据库表结构发生改变,或者一些指定的表数据需要更新.这也就引出一个问题Android数据库的更新问题. Android数据库升级分类 Android数据库更新 ...

  2. 优雅的处理Android数据库升级的问题

    原始完成于:2015-04-27 19:28:22 提供一种思路,优雅的处理Android数据库升级的问题,直接上代码: 1 package com.example.databaseissuetest ...

  3. Android 数据库升级解决方案

    转自:http://blog.csdn.net/leehong2005/article/details/9128501 请考虑如下情况: 在数据库升级时,不同版本的数据库,他们定义的表结构完全可能是不 ...

  4. Android数据库升级、降级、创建(onCreate() onUpgrade() onDowngrade())[4]

    数据库版本升级对软件的管理操作. 我们手机经常会收到xxx软件升级什么的提醒,你的软件版本更新,同时你的数据库对应的版本也要相应的更新. 数据库版本更新需要主要的问题: 软件的1.0版本升级到1.1版 ...

  5. Android数据库升级、降级、创建(onCreate() onUpgrade() onDowngrade())的注意点

    以下内容可以作为面试官在面试的时候的问题,感觉比较好,是比较常用的知识点,可以用来考察基础是否扎实. 也可以程序猿学习.开发中的注意点.因为稍微不注意,就有可能导致数据库不能用. DBAdapter. ...

  6. Android数据库升级不丢失数据解决方案

    在Android开发中,sqlite至关重要,增删查改不多说,难点在于,1,并发,多个线程同时操作数据库.2,版本升级时,如果数据库表中新加了个字段,如何在不删除表的情况下顺利过渡,从而不丢失数据. ...

  7. Android数据库升级实例

    第一部分 Andoird的SQLiteOpenHelper类中有一个onUpgrade方法.帮助文档中只是说当数据库升级时该方法被触发.经过实践,解决了我一连串的疑问: 1. 帮助文档里说的“数据库升 ...

  8. Android 数据库升级中数据保持和导入已有数据库

    一.数据库升级: 在我们的程序中,或多或少都会涉及到数据库,使用数据库必定会涉及到数据库的升级,数据库升级带来的一些问题,如旧版本数据库的数据记录的保持,对新表的字段的添加等等一系列问题,还记得当我来 ...

  9. Android数据库升级,数据不丢失解决方案

    假设要更新TableC表,建议的做法是: 1) 将TableC重命名为TableC_temp SQL语句可以这样写:ALERT TABLE TableC RENAME TO TableC_temp; ...

随机推荐

  1. NSIS:静默释放文件并运行 制作绿色单文件软件

    原文 NSIS:静默释放文件并运行 制作绿色单文件软件 现在所谓的绿色单文件软件,大多与以下代码原理相似:把软件运行需要的文件封装为一个EXE文件,双击时释放到某个目录(大多是TEMP)并运行主程序文 ...

  2. ios7 JavaScriptCore.framework

    曾经想要oc调用js代码通常是通过uiwebview的stringByEvaluatingJavaScriptFromString方法,或是直接使用JavaScriptCore引擎,比如https:/ ...

  3. zoj2977Strange Billboard (国家压缩+罗列)

    Strange Billboard Time Limit: 2 Seconds Memory Limit: 65536 KB The marketing and public-relations de ...

  4. sharepoint 2013 配件控制FileUpload如何检查是否图像的方法

    它记录的附件控制FileUpload如何检查是否图像的方法: function checkImg() { var fileObj =document.getElementById('<%=Fil ...

  5. css 鼠标提示样式预览表[转]

    语法: cursor : auto | all-scroll | col-resize| crosshair | default | hand | move | help | no-drop | no ...

  6. jvm对大对象分配内存的特殊处理(转)

    前段日子在和leader交流技术的时候,偶然听到jvm在分配内存空间给大对象时,如果young区空间不足会直接在old区切一块过去.对于这个结论很好奇,也比较怀疑,所以就上网搜了下,发现还真有这么回事 ...

  7. [Android] Upload package to device fails #2720

    错误描述: 解决办法:   来源:https://facebook.github.io/react-native/docs/android-setup.html

  8. linux_安装_安装编译phantomjs 2.0的方法_转

    项目中要对数据公式webkit渲染,phantmjs 2.0的效果好比1.9好不少. 安装过程中 坑比较多. 转载文章: phantomjs 2.0最新版的官方不提供编译好的文件下载,只能自己编译,有 ...

  9. javascript的语法作用域你真的懂了吗

    原文:javascript的语法作用域你真的懂了吗 有段时间没有更新了,思绪一下子有点转不过来.正应了一句古话“一天不读书,无人看得出:一周不读书,开始会爆粗:一月不读书,智商输给猪.”.再加上周五晚 ...

  10. 【高德地图API】如何打造十月妈咪品牌地图?

    原文:[高德地图API]如何打造十月妈咪品牌地图? 摘要:品牌地图除了地图,商铺标点外,还有微博关注,路线查询等功能. ---------------------------------------- ...