DButils数据库升级不丢失数据

如果版本升级,表中新增了某个字段,如何在不删除表的情况下顺利过渡,如果不做处理,数据库就会报错,没有新添加的列。修改数据库的创建方式,实现升级接口。

 1 db = DbUtils.create(context, "myXutils.sqlite",
 2                 DBVERSION, new DbUpgradeListener() {
 3 
 4                     @Override
 5                     public void onUpgrade(DbUtils db, int oldVersion,
 6                             int newVersion) {
 7                         if (newVersion > oldVersion) {
 8                             updateDb(db, "mytable");
 9                         }
10                     }
11                 });
 1 protected void updateDb(DbUtils db, String tableName) {
 2         try {
 3             // 把要使用的类加载到内存中,并且把有关这个类的所有信息都存放到对象c中
 4             Class<EntityBase> c = (Class<EntityBase>) Class
 5                     .forName("com.myxutils.entity" + tableName);
 6             if (db.tableIsExist(c)) {
 7                 List<String> dbList = new ArrayList<String>();
 8                 String sql = "select * from" + tableName;
 9                 Cursor cursor = db.execQuery(sql);
10                 int count = cursor.getColumnCount();
11                 for (int i = 0; i < count; i++) {
12                     dbList.add(cursor.getColumnName(i));
13                 }
14                 cursor.close();
15                 // 把属性的信息提取出来,并且存放到field类的对象中,因为每个field的对象只能存放一个属性的信息所以要用数组去接收
16                 Field f[] = c.getDeclaredFields();
17                 for (int i = 0; i < f.length; i++) {
18                     String fildName = f[i].getName();
19                     if (fildName.equals("serialVersionUID")) {
20                         continue;
21                     }
22                     String fildType = f[i].getType().toString();
23                     if (!dbList.contains(fildName)) {
24                         if (fildType.equals("class.Java.lang.String")) {
25                             db.execNonQuery("alter table " + tableName + "add"
26                                     + fildName + "TEXT");
27                         } else if (fildType.equals("int")
28                                 || fildType.equals("long")
29                                 || fildType.equals("boolean")) {
30                             db.execNonQuery("alter table " + tableName + "add"
31                                     + fildName + "INTEGER");
32                         }
33                     }
34                 }
35             }
36         } catch (ClassNotFoundException e) {
37             e.printStackTrace();
38         } catch (DbException e) {
39             e.printStackTrace();
40         }
41 
42     }
原文地址:https://www.cnblogs.com/tutuskys/p/5089290.html