android sqlite 判断表和表中字段是否存在方法

2023-02-10 19:43:17 浏览数 (3)

代码语言:javascript复制
/**
代码语言:javascript复制
    *检查某表是否存在
    * @param tableName 表名
    * @return  true:存在  false:不存在
    */


public boolean tabIsExist(String tabName){
        boolean result = false;
        if(tabName == null){
                return false;
        }
        Cursor cursor = null;
        try {
               
                String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" tabName.trim() "' ";
                cursor = mUDB.rawQuery(sql, null);
                if(cursor.moveToNext()){
                        int count = cursor.getInt(0);
                        if(count>0){
                                result = true;
                        }
                }
                
        } catch (Exception e) {
        }                
        return result;
}


/**
    *检查表中某列是否存在
    * @param db
    * @param tableName 表名
    * @param columnName 列名
    * @return  true:存在  false:不存在
    */
    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("","checkColumnExists2..."   e.getMessage()) ;
        }finally{
            if(null != cursor && !cursor.isClosed()){
                cursor.close() ;
            }
        }


        return result ;
    }

0 人点赞