android数据库升级的措辞
在基类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数据库升级的措辞的更多相关文章
- Android数据库升级
随着Android应用版本的迭代,经常遇到数据库表结构发生改变,或者一些指定的表数据需要更新.这也就引出一个问题Android数据库的更新问题. Android数据库升级分类 Android数据库更新 ...
- 优雅的处理Android数据库升级的问题
原始完成于:2015-04-27 19:28:22 提供一种思路,优雅的处理Android数据库升级的问题,直接上代码: 1 package com.example.databaseissuetest ...
- Android 数据库升级解决方案
转自:http://blog.csdn.net/leehong2005/article/details/9128501 请考虑如下情况: 在数据库升级时,不同版本的数据库,他们定义的表结构完全可能是不 ...
- Android数据库升级、降级、创建(onCreate() onUpgrade() onDowngrade())[4]
数据库版本升级对软件的管理操作. 我们手机经常会收到xxx软件升级什么的提醒,你的软件版本更新,同时你的数据库对应的版本也要相应的更新. 数据库版本更新需要主要的问题: 软件的1.0版本升级到1.1版 ...
- Android数据库升级、降级、创建(onCreate() onUpgrade() onDowngrade())的注意点
以下内容可以作为面试官在面试的时候的问题,感觉比较好,是比较常用的知识点,可以用来考察基础是否扎实. 也可以程序猿学习.开发中的注意点.因为稍微不注意,就有可能导致数据库不能用. DBAdapter. ...
- Android数据库升级不丢失数据解决方案
在Android开发中,sqlite至关重要,增删查改不多说,难点在于,1,并发,多个线程同时操作数据库.2,版本升级时,如果数据库表中新加了个字段,如何在不删除表的情况下顺利过渡,从而不丢失数据. ...
- Android数据库升级实例
第一部分 Andoird的SQLiteOpenHelper类中有一个onUpgrade方法.帮助文档中只是说当数据库升级时该方法被触发.经过实践,解决了我一连串的疑问: 1. 帮助文档里说的“数据库升 ...
- Android 数据库升级中数据保持和导入已有数据库
一.数据库升级: 在我们的程序中,或多或少都会涉及到数据库,使用数据库必定会涉及到数据库的升级,数据库升级带来的一些问题,如旧版本数据库的数据记录的保持,对新表的字段的添加等等一系列问题,还记得当我来 ...
- Android数据库升级,数据不丢失解决方案
假设要更新TableC表,建议的做法是: 1) 将TableC重命名为TableC_temp SQL语句可以这样写:ALERT TABLE TableC RENAME TO TableC_temp; ...
随机推荐
- HDU 1272 小希迷宫(并检查集合)
意甲冠军:被判处无向图无环和连接无处不在 思考:并检查集合,trap 您可能有一个直接输入0 0 并且....合并的时候按某一个方向会爆栈,爆了好几次...下次考虑一下直接递归找祖先吧 #includ ...
- Android L中间RecyclerView 、CardView 、Palette使用
RecyclerView CardView Palette <Material Design>提到,Android L版本号中新增了RecyclerView.CardView .Palet ...
- 站长VS微商 你选择哪个?
近期,站长圈里盛行起了一阵面膜风.我刷空间和微信朋友圈的时候,常常看到一些朋友在卖面膜,不光女童鞋在卖,男屌丝站长也在卖. 不光普通人在卖.行业圈的自媒体明星大佬也在卖. 我们暂且称卖面膜的童鞋为微商 ...
- cocos2d-x由Jni实现Java与C++打电话给对方
cocos2d-x由Jni实现Java与C++打电话给对方. cocos2d-x与开发商提供一个类JniHelper,提供java与c++之间的互jni解. 笔者所开发的"史上最坑爹的游戏& ...
- hdu 2067 兔子板
兔子板 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submis ...
- .NET开发者必备的11款免费工具
原文:.NET开发者必备的11款免费工具 如今,HTML5,jQuery,JavaScript等等这些热门技术,受到了开发者们的强烈追捧,有了这些开发工具也为开发者们减轻了许多负担.本文为开发者介绍了 ...
- JQuery插件开发初探——图片轮播
在熟悉了插件开发的结构以后,自己尝试着做了一个稍微复杂一点的小功能:图片轮播插件. 由于之前使用的一款图片轮播插件,性能不高,页面加载的时候需要载入全部的图片,因此速度很慢. 通过自己做这个小插件,能 ...
- 一个用于每一天JavaScript示例-SVG中间javaScript画廊
<?xml version="1.0" standalone="no"? > <!DOCTYPE svg PUBLIC "-//W3 ...
- oracle 11g 自己主动调整
--:自己主动调教计划 begin dbms_workload_repository.create_snapshot(); end; select /*+ result_cache */ coun ...
- Saving HDU (贪心)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2111 好久不刷题,拿到水题切了切,,,,,题意刚开始都没有理解,,,,真是弱了,,,, 简单贪心,,, ...