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%'

转载于:https://www.cnblogs.com/finersoft/p/5666428.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值