一下只是简单的介绍一下OrmLite 数据库的升级用法
在我们开发的过程中,难免会因为增加字段,或者增加新表,从而引发数据库的升级,升级的同时又不能简单粗暴的删除旧表的数据,此时,就要用到我今天要介绍给大家的一个方法了,本人亲测有效,废话不多说,上代码!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1.引入依赖
implementation files('libs/ormlite-android-5.0.jar')
2.创建数据库
需要创建一个类来继承OrmLiteSqliteOpenHelper,完成数据的创建以及升级
DetailDataOpenHelper.java
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 = "my_sqlite.db";
private Map daos = new HashMap();
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 database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.createTable(connectionSource, Person3333.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
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;
}
}
}
onCreate 初始化数据库
调用TableUtils.createTable(connectionSource, Person.class);
onUpgrade 升级数据库
先删除表,调用TableUtils.dropTable(connectionSource, IdentityInfo.class, false);
然后创建表,调用TableUtils.createTable(connectionSource, IdentityInfo.class);
创建JavaBean
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "persons")
public class Person {
@DatabaseField(id = true)
private String name;
@DatabaseField
private String password;
public Person() {
}
public Person(String s, String s1) {
name=s;
password=s1;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
注解含义
@DatabaseTable(tableName = "person"),此处指创建了一个的t_person的表
@DatabaseField(columnName = "id", generatedId = true),此处指创建了名为id的字段名,且是主键
@DatabaseField(columnName = "personName"),此处指创建了名为personName的字段名
常用参数
generatedId = true 主键,自动生成的id 该注解下的字段必须是整形(int long)
id = true 主键
unique = true 唯一约束 默认false
columnName = "name" 表字段名,默认为变量名称
canBeNull = false 非空约束,默认为true,可以为null,设为false就不能为null
foreign = true 外键引用,字段不能是一个原始类型,应该定义一个对象当做外键引用,在外键对象的类中,必须要有一
个ID字段(ID, generatedId,generatedIdSequence)
foreignAutoRefersh = true 在使用外键引用时,由于ormlite的外键引用使用的是对象,所以添加这个字段的话在查询,会把
外键的对象数据都查询回来,否则外键数据就只有那个对象的主键有值,其余的值都是null
defaultValue = "小明" 默认值
index = true 建立索引 默认为false
uniqueIndex = true 唯一索引 默认为false
创建PersonDao
import android.content.Context;
import com.j256.ormlite.dao.Dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lsj on 2015/11/9.
*/
class UserDao {
private Context context;
private Dao userDaoOpe;
private DatabaseHelper helper;
public UserDao(Context context) {
this.context = context;
try {
helper = DatabaseHelper.getHelper(context);
userDaoOpe = helper.getDao(Person.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
public UserDao() {
}
/**
* 添加一个用户
* @param user
*/
public void add(ArrayList user) {
try {
userDaoOpe.create(user);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 查询全部数据
* @return
*/
public List query(){
List fpList = null;
try {
fpList =userDaoOpe.queryBuilder().query();
} catch (SQLException e) {
e.printStackTrace();
}
return fpList;
}
/**
* 清空所有记录信息
*
* @return
*/
public void deleteAll() {
try {
userDaoOpe.queryRaw("DELETE\n" +
"FROM\n" +
"\tpersons");
userDaoOpe.queryRaw("UPDATE sqlite_sequence\n" +
"SET seq = 0\n" +
"WHERE\n" +
"\tname = 'persons'");
} catch (SQLException e) {
}
}
}
这里只做简单的介绍使用在Activity中
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
/**
* 插入
*/
private Button mBtn1;
/**
* 删除
*/
private Button mBtn2;
/**
* 修改
*/
private Button mBtn3;
/**
* 查询
*/
private Button mBtn4;
private Button mBtn5;
private Button mBtn6;
/**
* Hello World!
*/
private TextView mTv;
private Person person;
private UserDao dao;
private UserDao1 dao1;
private UserDao33 dao3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
dao = new UserDao(this);//初始化第一张表
dao3 = new UserDao33(this);//初始化第二张表
}
private void initView() {
mBtn1 = (Button) findViewById(R.id.btn1);
mBtn1.setOnClickListener(this);
mBtn2 = (Button) findViewById(R.id.btn2);
mBtn2.setOnClickListener(this);
mBtn3 = (Button) findViewById(R.id.btn3);
mBtn3.setOnClickListener(this);
mBtn4 = (Button) findViewById(R.id.btn4);
mBtn5 = (Button) findViewById(R.id.btn5);
mBtn4.setOnClickListener(this);;
mBtn6 = (Button) findViewById(R.id.btn6);
mBtn6.setOnClickListener(this);
mTv = (TextView) findViewById(R.id.tv);
mBtn5.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
case R.id.btn1://添加数据
person = new Person();
ArrayList people = new ArrayList<>();
people.add(new Person("smy","123"));
dao.add(people);
break;
case R.id.btn2:
ArrayList people33 = new ArrayList<>();
people33.add(new Person3333("smy","123"));
dao3.add(people33);
break;
case R.id.btn3://删除,清空表
dao1.deleteAll();
break;
case R.id.btn4://查询所有数据
List list = dao.query();
mTv.setText(list.toString());
break;
case R.id.btn5:
List list1 = dao1.query();
mTv.setText(list1.toString());
break;
case R.id.btn6://查询所有
List list3 = dao3.query();
mTv.setText(list3.toString());
break;
}
}
}
这样的话,简单的创表及增删改查的基本使用都介绍完了,下面才是真正的荤菜,数据库的升级之增加一张新表
升级数据库,最重要的就是版本号递增,以及旧表及新表的删除,迁移数据,创建新表的语法使用了
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 7);//最后的数字就是版本号,没升级的时候自己去手动修改增加就好了
}
升级主要就是在以下这个方法中执行,升级的数据库不会走oncreate方法,直接走以下这个方法进行更新,所以新增表的情况下,直接调用api,放入你要创建的新的表就行了(千万不要忘记版本号去修改)这样就避免了旧表数据的丢失
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.createTable(connectionSource, Person3333.class);
} catch (SQLException e) {
e.printStackTrace();
}
}