博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
sqlite 查询表和字段是否存在
阅读量:4673 次
发布时间:2019-06-09

本文共 1515 字,大约阅读时间需要 5 分钟。

原文摘自 

一般数据库升级时,需要检测表中是否已存在相应字段(列),因为列名重复会报错。方法有很多,下面列举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的系统表  来查找相应表里是否存在该字段,稍微换下语句也可以查找表是否存在

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

你可能感兴趣的文章
调试程序Bug-陈棚
查看>>
STM32 寄存器库和固件库
查看>>
第11周表格
查看>>
linux运维云计算课程学习,Linux云计算面试时遇到的问题
查看>>
Abiword对话框资源
查看>>
跟我一起写 Makefile
查看>>
C# uri
查看>>
GPS定位 测试
查看>>
前端使用AngularJS的$resource,后端ASP.NET Web API,实现增删改查
查看>>
探索从 MVC 到 MVVM + Flux 架构模式的转变
查看>>
tornado的异步效果
查看>>
*2.3.2_加入env
查看>>
JS中SetTimeOut和SetInterval方法的区别?
查看>>
Protocol Buffers proto语言语法说明
查看>>
Hibernate双向一对一对象关系模型映射
查看>>
正则表达式(下)
查看>>
熟悉常用的HDFS操作
查看>>
Linux自动化运维第十八课
查看>>
web 10
查看>>
jquery--动态篇
查看>>