您的位置:首页 > 数据库

实践--升级数据库最佳写法

2016-04-04 19:10 507 查看
当我们第一次建表的时候这样写

public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;

public static  final String CREATE_STUDENT="create table book(id integer primary key autoincrement,name text,age integer,clazz text)";

public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.context=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_STUDENT);
Toast.makeText(context, "数据库创建成功", Toast.LENGTH_SHORT).show();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}


一段时间之后,我们要添加一张表,但是之前表的数据还不能删除,我们可以这样写

public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;

public static  final String CREATE_STUDENT="create table book(id integer primary key autoincrement,name text,age integer,clazz text)";
public static  final String CREATE_HELLOWORD="create table helloword(id integer primary key autoincrement,name text,age integer,clazz text)";

public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.context=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_STUDENT);
//若是第一次建表,则将两个表都建立
db.execSQL(CREATE_HELLOWORD);
Toast.makeText(context, "数据库创建成功", Toast.LENGTH_SHORT).show();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion){
case 1:
//若已经有第一个版本的数据库,我们只增加一个表就可以了
db.execSQL(CREATE_HELLOWORD);
}
}
}


之后我们打算在第一个表中添加一个新的列字段

public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
//在其中新添加的sex字段
public static final String CREATE_STUDENT = "create table book(id integer primary key autoincrement,name text,age integer,clazz text,sex text)";
public static final String CREATE_HELLOWORD = "create table helloword(id integer primary key autoincrement,name text,age integer,clazz text)";

public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
//若是第一次建表,则将两个表全部建立就好
db.execSQL(CREATE_STUDENT);
db.execSQL(CREATE_HELLOWORD);
Toast.makeText(context, "数据库创建成功", Toast.LENGTH_SHORT).show();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
//若是已经安装过旧版本,根据相应版本号,添加相应的所缺的部分
case 1:
db.execSQL(CREATE_HELLOWORD);
case 2:
db.execSQL("alter table book add column sex text");
}
}
}


-这里有一个细节请注意,switch中,每一个case后面都没有使用break语句,这样可保证在跨版本升级的时候,每一次的数据库的修改都能被全部执行。比如说用户从第一版升级到第三版的时候。case 1和case 2中的逻辑就都会执行。

- 使用这种方式进行数据库的升级,不管版本怎么更新,都可以保证数据库的表结构是最新的,并且表中的数据也不会丢失。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: