动态添加列,可以避免更新数据库时删除表中数据;
/**
* 给现有表中添加列
*
* @param db
* @param tableName 表名
* @param columnName 列名
* @param columnType 列类型
* @param defaultField 列默认值
*/
public synchronized void updateColumn(SQLiteDatabase db, String tableName,
String columnName, String columnType,
Object defaultField) {
try {
if (null != db) {
//查询第一条记录
Cursor c = db.rawQuery("SELECT * from " + tableName + " limit 1 ",
null);
boolean flag = true;
if (c != null) {
//遍历检索是否已经存在该列
for (int i = 0; i < c.getColumnCount(); i++) {
if (columnName.equalsIgnoreCase(c.getColumnName(i))) {
flag = false;
break;
}
}
if (flag) {
//插入列
String sql = "alter table " + tableName + " add " + columnName + " "
+ columnType + " default " + defaultField;
db.execSQL(sql);
}
c.close();
}
}
} catch (Exception e) {
Log.d("nan", "表列更新失败===" + columnName);
e.printStackTrace();
}
}
在函数onUpgrade中调用:
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
updateColumn(sqLiteDatabase, "表名", "需要添加的列名", "需要添加的列的类型", "该列的默认值");
}
网友评论