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

来源:互联网 发布:51单片机与esp8266例程 编辑:程序博客网 时间:2024/05/06 17:43

一般数据库升级时,需要检测表中是否已存在相应字段(列),因为列名重复会报错。方法有很多,下面列举2种常见的方式:

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

01/**

02* 方法1:检查某表列是否存在

03* @param db

04* @param tableName 表名

05* @param columnName 列名

06* @return

07*/

08private boolean checkColumnExist1(SQLiteDatabase db, String tableName

09        , String columnName) {

10    boolean result = false ;

11    Cursor cursor = null ;

12    try{

13        //查询一行

14        cursor = db.rawQuery( "SELECT * FROM " + tableName + " LIMIT 0"

15            , null );

16        result = cursor != null && cursor.getColumnIndex(columnName) != -1;

17    }catch (Exception e){

18         Log.e(TAG,"checkColumnExists1..." + e.getMessage()) ;

19    }finally{

20        if(null != cursor && !cursor.isClosed()){

21            cursor.close() ;

22        }

23    }

24 

25    return result ;

26}

2、通过查询sqlite的系统表sqlite_master来查找相应表里是否存在该字段,稍微换下语句也可以查找表是否存在

查看源代码打印帮助

01/**

02* 方法2:检查表中某列是否存在

03* @param db

04* @param tableName 表名

05* @param columnName 列名

06* @return

07*/

08private boolean checkColumnExists2(SQLiteDatabase db, String tableName

09       , String columnName) {

10    boolean result = false ;

11    Cursor cursor = null ;

12 

13    try{

14        cursor = db.rawQuery( "select * from sqlite_master where name = ? and sql like ?"

15           , new String[]{tableName , "%" + columnName + "%"} );

16        result = null != cursor && cursor.moveToFirst() ;

17    }catch (Exception e){

18        Log.e(TAG,"checkColumnExists2..." + e.getMessage()) ;

19    }finally{

20        if(null != cursor && !cursor.isClosed()){

21            cursor.close() ;

22        }

23    }

24 

25    return result ;

26}

1方法好像其他系统不能用  

2方法改动如下

select count(*) from sqlite_master where name = 't_phb' and sql like '%[name]%';

根据返回值就知道是否存在

0 0
原创粉丝点击