android 检测sqlite数据表和表中字段(列)是否存在 (转)

android 检测sqlite数据表是否存在html

/**
     * 方法:检查某表是否存在
     */
    synchronized public boolean isTableExist(String tableName) {
        boolean result = false;
        if (tableName == null) {
            return false;
        }
        SQLiteDatabase db;
        Cursor cursor;
        try {
            db = dbHelper.getWritableDatabase();
            if (db.isOpen()) {
                String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + tableName.trim() + "' ";
                cursor = db.rawQuery(sql, null);
                if (cursor.moveToNext()) {
                    int count = cursor.getInt(0);
                    if (count > 0) {
                        result = true;
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return result;
    }java


android 检测sqlite数据表中字段(列)是否存在 (转)
android

原文摘自 http://www.tuicool.com/articles/jmmMnusql

通常数据库升级时,须要检测表中是否已存在相应字段(列),由于列名重复会报错。方法有不少,下面列举2种常见的方式:数据库

一、根据 cursor.getColumnIndex(String columnName) 的返回值判断,若是为-1表示表中无此字段ui

/**
* 方法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 ;
}

二、经过查询sqlite的系统表 sqlite_master 来查找相应表里是否存在该字段,稍微换下语句也能够查找表是否存在spa

/**
* 方法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 ;
}
相关文章
相关标签/搜索