Android sqlite版本更新大致方案

来源:互联网 发布:淘宝包包代销货源 编辑:程序博客网 时间:2024/05/24 06:38

设想这样的情景:一个app的1.0版本聊天记录存在数据库里,比如字段有三个:user Id,userName,content

现在我在2.0版本中要优化这个模式,添加上一个消息时间的字段:time,这时就涉及到数据库版本更新的问题。


1、为什么要更新数据库:安装1.0版本的用户的聊天记录缓存在本地,它的字段有三个,如果用户更新了应用,2.0版本的程序在读取第四个字段time时由于缓存的表里没有time就会报空指针

2、基于1的问题,那要不把缓存的数据库删掉吧,重新命名一个数据库,这样更不可以,难道你微信每次更新聊天记录就没有了吗?

基于上面的问题的解决方案:利用SQLiteOpenHelper的onUpgrade方法

public class DBservice extends SQLiteOpenHelper{    private String CREATE_CHATTABLE = "create table chattable(userId integer primarykey,userName text,content text);";    //备份1.0版本数据库,命名为temp    private String CREATE_TEMP_CHATTABLE = "alter table chattable rename to _temp_chattable";    //把temp表中的用户缓存的数据导入新创建的数据库表中 ----''是为新加入字段插入默认值必须加上的,否则报错<pre name="code" class="java"><span style="font-size:10px;">     </span>private String INSERT_DATA = "insert into chattable select *,'' from _temp_chattable";    //temp表的数据已经转移,那么就删除temp表    private String DROP_CHATTABLE = "drop table _temp_chattable"; public DBservice(Context context, String name, CursorFactory factory,int version) {  super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) {  db.execSQL(CREATE_CHATTABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  switch (newVersion) {  case 2:   db.execSQL(CREATE_TEMP_CHATTABLE);   //此处不会报table chattable already exists  因为一旦检测到数据库版本升级,会对客户端缓存的数据库重命名为temp,所以再次创建的时候是不会报错的   db.execSQL(CREATE_CHATTABLE);   db.execSQL(INSERT_DATA);   db.execSQL(DROP_CHATTABLE);   break;  } }

注释写的很清楚不在多说


1 0
原创粉丝点击