FMDB-查看表是否存在
以前总结过一篇FMDB使用方法:https://www.jianshu.com/p/7958d31c2a97 ,但是发现基本的增删改查数据库已经不能满足自用了,现总结几个问题,方便后期查看
- 查找数据库中某一个表是否存在:
sql语句:
SELECT COUNT(*) count FROM sqlite_master where type='table' and name='studyTime'
type:'table' 固定写法
name:表名字
如果count=1 说明表存在, count=0 说明表不存在,不存在的话创建表
代码如下:
NSString *findSql = [NSString stringWithFormat:@"SELECT COUNT(*) count FROM sqlite_master where type='table' and name='studyTime'"];
rs = [dbPointer executeQuery:findSql];
if ([rs next]) {
NSString *count=[rs stringForColumn:@"count"];
if (count.intValue == 0) {
NSString *findSql1 = [NSString stringWithFormat:@"CREATE TABLE studyTime (timeId integer NOT NULL PRIMARY KEY,userId integer NOT NULL DEFAULT 0,seconds integer NOT NULL DEFAULT 0,date varchar,beginTime varchar,endTime varchar)"];
[dbPointer executeUpdate:findSql1];
}
}
- 查询表中某一个字段是否存在
sql语句:
[dataBase columnExists:@"addrURL" inTableWithName:@"iseScore"]
columnExists:字段名
inTableWithName:表名字
返回YES代表表中存在某个字段,返回NO表示不存在。
- 向表中插入某一个字段
sql语句:
alter table iseScore add column addrURL text
iseScore:表名
addrURL: 插入的字段名
text:表示字段名的类型
代码如下:
FMDatabase *dataBase = [WJQISERecord setupIsedatabase];
if (![dataBase columnExists:@"addrURL" inTableWithName:@"iseScore"]) {
BOOL add = [dataBase executeUpdate:@"alter table iseScore add column addrURL text"];
if (add) {
NSLog(@"add success");
} else {
NSLog(@"add fail");
}
}
- 删除某一张表
sql语句:
delete from iseScore_British
iseScore_British:表名字
代码如下:
NSString *findSql = [NSString stringWithFormat:@"delete from iseScore_British"];
if ([dataBase executeUpdate:findSql]) {
}
- 查询表中某个字段最大或者最小数据
sql语句:
select max(recordId) last from iseRecord
iseRecord:表名字
recordId:字段名
代码如下:
NSString *findSql = [NSString stringWithFormat:@"select max(recordId) last from iseRecord"];
rs = [dataBase executeQuery:findSql];
- 查询表中某一个字段的数据
sql语句:
查询voaid=1031固定数据的count:
select count(*) from voadetail where Voaid = 1031
或者查询voaid=1xxx的所有数据:
select count(*) from voadetail where Voaid like '1%%%'
voadetail:表名字
Voaid:字段名
代码如下:
FMDatabase *db = [database setup];
[db intForQuery:@"select count(*) from voadetail where Voaid = 1031"];
[db intForQuery:@"SELECT count(*) FROM voa WHERE VoaId LIKE '1\%%%'"];
本篇先记录到此,感谢阅读,如有错误,不吝赐教!