SQLite DBHelper 跨版本更新数据库

来源:互联网 发布:linux 禁止ip访问 编辑:程序博客网 时间:2024/05/21 04:22

在跨版本升级的时候,每一次的数据库修改都能被全部执行到。
比如用户当前是从第二版程序升级到第三版程序的,那么case 2 中的逻辑就会执行。
而如果用户是直接从第一版程序升级到第三版程序的,那么case 1 和case 2 中的逻辑都会执行。使用这种方式来维护数据库的升级,不管版本怎样更新,都可以保证数据库的表结构是最新的。

public class MyDBHelper extends SQLiteOpenHelper {    private Context mcontext;    public static final String  CREATE_BOOK="create table book("                                              +"id integer primary key autoincrement,"                                              +"author text,"                                              +"price real,"                                              +"name text)"                                              ;    public static final String CREATE_CATEGORY="create table category("                                             +"id integer primary key autoincrement,"                                             +"category_name text,"                                             +"category_code integer)";    public MyDBHelper(Context context, String name, CursorFactory factory,            int version) {        super(context, name, factory, version);        mcontext=context;    }    @Override    public void onCreate(SQLiteDatabase db) {        db.execSQL(CREATE_BOOK);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        switch(oldVersion){          case 1: //更新数据库时分级更新,每一个case后没有break              db.execSQL(CREATE_BOOK);          case 2:              db.execSQL(CREATE_CATEGORY);          case 3:              db.execSQL("alter table book add column category_id integer");          break;        }    }}
0 0
原创粉丝点击