前言
在之前的文章中已经进行过简单的介绍ormlite数据库的简单的操作使用(包含 增 删 改 查 等...),以及包含了库表简单暴力的升级方法,直接删除旧表,更改版本号,重新创建库表的操作.
今天
应粉丝的要求,来更新一篇此库表的 增加字段库表升级的方法介绍,即 保留旧表的数据,增加新的字段数据,同时
升级库表版本号的完美操作,废话不多,直接上代码
这是库表锁对应的实体类(这是已经新增的两个字段 age sex)
@DatabaseTable(tableName = "persons")
public class Person {
@DatabaseField(id = true)
private String name;
@DatabaseField
private String password;
@DatabaseField
private String age;
@DatabaseField
private String sex;
这是库表版本号(我默认原始版本号为7,当然你自己根据实际情况来定)
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 7);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Person.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
if(oldVersion < 7){//暂不说明为何要这么判断
DatabaseUtil.upgradeTable(db,connectionSource,Person.class,DatabaseUtil.OPERATION_TYPE.ADD);
}
onCreate(db,connectionSource);
}
工具类(迁移库表数据所需要用到的,直接贴到你的项目中就行)
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String TABLE_NAME = "person.db";
private Map<String, Dao> daos = new HashMap<String, Dao>();
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 7);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Person.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
if(oldVersion < 7){//暂不说明为何要这么判断
DatabaseUtil.upgradeTable(db,connectionSource,Person.class,DatabaseUtil.OPERATION_TYPE.ADD);
}
onCreate(db,connectionSource);
}
private static DatabaseHelper instance;
/**
* 单例获取该Helper
*
* @param context
* @return
*/
public static synchronized DatabaseHelper getHelper(Context context) {
context = context.getApplicationContext();
if (instance == null) {
synchronized (DatabaseHelper.class) {
if (instance == null){
instance=new DatabaseHelper(context);
}
}
}
return instance;
}
public synchronized Dao getDao(Class clazz)throws SQLException{
Dao dao=null;
String className=clazz.getSimpleName();
if(daos.containsKey(className)){
dao=daos.get(className);
}
if(dao==null){
dao=super.getDao(clazz);
daos.put(className,dao);
}
return dao;
}
/**
* 释放资源
*/
@Override
public void close() {
super.close();
for(String key:daos.keySet()){
Dao dao=daos.get(key);
dao=null;
}
}
}