android 检测sqlite数据表中字段(列)是否存在
一般数据库升级时,需要检测表中是否已存在相应字段(列),因为列名重复会报错。方法有很多,下面列举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 ; }
相关推荐
DAV数据库 2020-06-17
airfling 2020-05-31
zbcaicai 2020-05-26
beibeijia 2020-04-25
Rain 2020-04-16
Plant 2020-04-08
园搬家测试账号 2020-03-25
MFCJCK 2020-02-24
xiaoxiangyu 2020-02-23
Plant 2020-02-03
CharlesYooSky 2020-02-01
MFCJCK 2020-01-31
nxcjh 2020-01-29
wintershii 2020-01-18
zbcaicai 2020-01-03
MFCJCK 2019-12-30
airfling 2019-12-28
Plant 2019-12-27
Dlanguage 2019-12-27
Dlanguage 2019-12-25
whyname 2019-12-23