一般数据库升级时,或者为满足需求新增加某些字段,需要检测表中是否已存在相应字段(列),因为列名重复会报错。方法有很多,下面列举2种常见的方式:
1、根据 cursor.getColumnIndex(String columnName) 的返回值判断,如果为-1表示表中无此字段/**
* 方法1:检查某表列是否存在
* @param db
* @param tableName 表名
* @param columnName 列名
* @return 布尔值结果
*/
private boolean isColumnExist(SQLiteDatabase db, String tableName
, String columnName) {
boolean result = false ;
Cursor cursor = null ;
try{
//查询一行
cursor = db.rawQuery( "SELECT * FROM " + tableName + " LIMIT 0"
, null );
result = cursor != null && cursor.getColumnIndex(columnName) != -1 ;
}catch (Exception e){
Log.e(TAG,"checkColumnExists1..." + e.getMessage()) ;
}finally{
if(null != cursor && !cursor.isClosed()){
cursor.close() ;
}
}
return result ;
}
2、通过查询sqlite的系统表 sqlite_master 来查找相应表里是否存在该字段,从判断表是否存在改过来的/**
* 方法2:检查表中某列是否存在
* @param db
* @param tableName 表名
* @param columnName 列名
* @return 布尔值结果
*/
private boolean isColumnExists(SQLiteDatabase db, String tableName
, String columnName) {
boolean result = false ;
Cursor cursor = null ;
try{
cursor = db.rawQuery( "select * from sqlite_master where name = ? and sql like ?"
, new String[]{tableName , "%" + columnName + "%"} );
result = null != cursor && cursor.moveToFirst() ;
}catch (Exception e){
Log.e(TAG,"checkColumnExists2..." + e.getMessage()) ;
}finally{
if(null != cursor && !cursor.isClosed()){
cursor.close() ;
}
}
return result ;
}
在项目开发中使用的情况:往往是需要添加列的/**
* 只适合于在后面加一个int字段
*
* @return true 表示已经有了该字段,是最新版的数据库,false 反之..
*/
public boolean checkTableCul(String tableName, String culName) {
boolean result = false;
Cursor cursor = null;
try {
HashMap maps = new HashMap();
maps.put("[" + culName + "]", " int DEFAULT (0)"); // DEFAULT (0)
cursor = getDataBase().rawQuery("select sql from sqlite_master where type='table' and " +
"name=?", new String[]{tableName});
if (cursor != null && cursor.moveToFirst()) {
String sql = cursor.getString(0);
if (!StringUtils.isNullOrEmpty(sql)) {
Iterator ite = maps.keySet().iterator();
while (ite.hasNext()) {
String st = ite.next() + " ";
if (sql.contains(st)) {
ite.remove();
}
}
}
}
if (!maps.keySet().contains("[" + culName + "]")) {
result = true;
}
for (String st : maps.keySet()) {
addCol(getDataBase(), tableName, st, maps.get(st));
}
} catch (Exception e) {
LogManager.e("oncreatedb", e);
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
return result;
}
void addCol(SQLiteDatabase db, String tableName, String col, String type) {
if (db != null) {
db.execSQL(new StringBuffer().append("alter table ").append(tableName)
.append(" add ").append(col).append(" ").append(type).toString());
}
}