原文摘自 http://www.tuicool.com/articles/jmmMnu
一般數據庫升級時,需要檢測表中是否已存在相應字段(列),因為列名重復會報錯。方法有很多,下面列舉2種常見的方式:
1、根據 cursor.getColumnIndex(String columnName) 的返回值判斷,如果為-1表示表中無此字段
/** * 方法1:檢查某表列是否存在 * @param db * @param tableName 表名 * @param columnName 列名 * @return */ private boolean checkColumnExist1(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 checkColumnExists2(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 ; }