iOS - FMDB使用
2022-11-07 本文已影响0人
FieryDragon
SQLite语法可参考SQLite 教程。本篇仅记录项目中使用的一些基础用法。
常用数据类型
NULL NULL值
REAL 浮点型(如CGFloat、float、double;需要转成NSNumber)
INTEGER 整型(如NSInteger、int;需要转成NSNumber)
TEXT 文本类(如NSString)
BLOB 二进制(如图片、文件NSData等)
创建库
- (void)createTable {
[self.queue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
if (0 == db.userVersion) {
[db setUserVersion:DB_SPORT_VERSION];
}
//如果不存在girls_table,则创建它
[db executeUpdate:@"create table if not exists sport_data (\
//主键logID,自增长
logID integer primary key autoincrement,\
//创建sportId,字符类型,不为null,唯一,默认''
sportId text not null unique default '',\
//创建sportLocation,字符类型,不为null,默认''
sportLocation text not null default '',\
//创建useTime,浮点类型,默认0
useTime REAL not null default 0,\
mileage REAL not null default 0.00,\
speed text not null default 0.00,\
//创建createTime,日期已浮点类型存储,默认0
createTime REAL not null default 0,\
endTime REAL not null default 0,\
//创建isStudent,无BOOL类型此处用int代替,默认0
isStudent integer not null default 0,\
//创建isStudent,int类型,默认0
dataStatus integer not null default 0,\
imagesStatus integer not null default 0)"];
[db executeUpdate:@"create table if not exists sport_image_data (\
logID integer primary key autoincrement,\
sportId text not null default '',\
imageName text,\
updateTime text not null default '0',\
imageStatus integer not null default 0)"];
}];
}
sport.png
image.png
升级
const static uint32_t DB_SPORT_VERSION = 1;
#pragma mark -数据库表更新
- (void)upgrade {
[self.queue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
uint32_t oldVersionNum = db.userVersion;
if (oldVersionNum >= DB_SPORT_VERSION) {
return;
}
[self upgrade:db version:oldVersionNum];
[db setUserVersion:DB_SPORT_VERSION];
}];
}
- (void)upgrade:(FMDatabase *)db version:(uint32_t)oldVersion {
if (oldVersion >= DB_SPORT_VERSION) {
return;
}
switch (oldVersion) {
case 1:
[db executeUpdate:@"ALTER TABLE sport_data ADD space INTEGER default 0"];
[db executeUpdate:@"CREATE TABLE *** (*****)"];
break;
case 2:
......
break;
case 3:
......
default:
break;
}
oldVersion ++;
[self upgrade:db version:oldVersion];
}
查询
其它
ORDER BY
ORDER BY 子句是用来基于一个或多个列按升序或降序顺序排列数据。
AND、 OR
AND 和 OR 运算符用于编译多个条件来缩小在 SQLite 语句中所选的数据。这两个运算符被称为连接运算符。这些运算符为同一个 SQLite 语句中不同的运算符之间的多个比较提供了可能。
[NSString stringWithFormat:@"SELECT * FROM Farmers WHERE bizId = '%@'AND farmerStatus !=2 AND (farmerName like '%%%@%%' OR checkResult like '%%%@%%') ORDER BY createdDate DESC",bizId,searchText,searchText]