zoukankan      html  css  js  c++  java
  • sqlite 查询表和字段是否存在

    原文摘自 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 ;
    }


    我用的方法2,然后用alter改了表结构后,一样可以查出来
    alter table yuhuolixian add aaa integer null
    select * from sqlite_master where name = 'yuhuolixian' and sql like '%aaa%'
  • 相关阅读:
    BZOJ1999或洛谷1099&BZOJ2282或洛谷2491 树网的核&[SDOI2011]消防
    BZOJ1912或洛谷3629 [APIO2010]巡逻
    CH6202 黑暗城堡
    POJ2728 Desert King
    JoyOI1391 走廊泼水节
    洛谷1073 最优贸易
    POJ3662或洛谷1948 Telephone Lines
    BZOJ1106 [POI2007]立方体大作战tet
    ubuntu 16.04 安装genymotion
    ubuntu下搭建android开发环境核心篇安装AndroidStudio、sdk、jdk
  • 原文地址:https://www.cnblogs.com/finersoft/p/5666428.html
Copyright © 2011-2022 走看看