iOS数据库FMDB
引言
在iOS应用开发中,数据库是数据持久化的一种方案(包括数据库SQLite、core data 、plist、archive、NSUerDefault)。由于系统原生的SQLite API在使用上相当不友好,在使用时,非常不便,于是就出现了一系列将SQLite API进行封装的库,例如FMDB、PlausibleDatabase、sqlitepersistentobjects等,在这库些中FMDB由于自身简单方便而被广大开发者所使用。FMDB:https://github.com/ccgus/fmdb
(一)FMDB的基本介绍
FMDB 同时兼容ARC与非ARC工程,会自动根据功臣的配置来调整相关的内存管理。
FMDB常用类:
FMDatabase:一个单一的数据库,用于执行SQL语句
FMResultSet:执行查询一个FMDatabase的结果集
FMDatabaseQueue:在多个线程来执行查询和更新数据库的数据
(二)数据库操作:
创建数据库
建表(创建一张表)
增(向表中插入新数据inset or replace into)
删(删除表中数据delete)
改 (修改数据库中当前已有的数据update)
查(查询语句select)
总结:数据库增删改等操作:除了查询操作,FMDB数据库操作都执行executeUpdate方法,这个方法返回BOOL型。
数据库查询操作: 查询操作使用了executeQuery,并涉及到FMResultSet。
(三)代码学习
在实际项目中一般使用databaseQueue,
创建数据库
- (void)openDBWithFileName:(NSString *)fileName dbName:(NSString *)dbName{
//首先判断传入的参数
if (!fileName.length || !dbName.length) {
return;
}
//获取文件目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, NO);
NSString *documentDirectory =[paths firstObject];
NSString *pathDirectory = nil;
if (fileName.length !=0 ) {
pathDirectory = [documentDirectory stringByAppendingPathComponent:fileName];
}
// 创建文件夹
if (![[NSFileManager defaultManager] fileExistsAtPath:pathDirectory]) {
NSError *error ;
[[NSFileManager defaultManager] createDirectoryAtPath:pathDirectory withIntermediateDirectories:YES attributes:nil error:&error];//参数YES,表示不管有没有这个文件夹都会去创建,如果参数为no,则 只会在没有这个文件夹的时候才会创建
if (error) {
NSLog(@"%@",[error description]);
}
}
//创建数据库
NSString *dbPath = [pathDirectory stringByAppendingPathComponent:dbName];
if (!_dbQueue) {
NSLog(@"%@",[FMDatabaseQueue databaseQueueWithPath:dbPath]);
self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
NSLog(@"%@__open",self.dbQueue);
}
}
插入数据
//单条数据的插入不用使用事务
- (BOOL)insertBasicUserInfo:(BasicUserInfoEntity *)basicInfo
{
__block BOOL ret = NO;
__weak UserInfoDao *weakSelf = self;
[[UserDaoHelper shareUserHelper].dbQueue inDatabase:^(FMDatabase *db) {
ret = [weakSelf insertBasicUserInfo:basicInfo db:db];
}];
return ret;
}
//多条插入使用数据库事务的方法:inTransaction
- (void)insertBasicInfos:(NSArray *)basicUserInfoArray
{
__weak UserInfoDao *weakSelf = self;
[[UserDaoHelper shareUserHelper].dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
for (BasicUserInfoEntity *userInfo in basicUserInfoArray) {
[weakSelf insertBasicUserInfo:userInfo db:db];
}
}];
}
- (BOOL)insertBasicUserInfo:(BasicUserInfoEntity *)basicInfo db:(FMDatabase *)db{
NSString *sql = @"insert or replace into BasicUserInfo(userId,nickName,age,gender) values(?,?,?,?)";
return [db executeUpdate:sql withArgumentsInArray:@[[NSNumber numberWithInteger:basicInfo.userId],
basicInfo.nickName,
[NSNumber numberWithInteger:basicInfo.age],
[NSNumber numberWithInteger:basicInfo.gender]]];
}
修改数据
- (void)updateBasicUserInfo:(NSInteger)gender userId:(NSInteger)userId
{
[[UserDaoHelper shareUserHelper].dbQueue inDatabase:^(FMDatabase *db) {
NSString *sql = [NSString stringWithFormat:@"update BasicUserInfo set gender = %ld where userId =%ld",(long)gender,(long)userId];
[db executeUpdate:sql];
} ];
}
删除表
- (void)deleteTable
{
[[UserDaoHelper shareUserHelper].dbQueue inDatabase:^(FMDatabase *db) {
NSString *sql = @"delete from BasicUserInfo";
[db executeUpdate:sql];
}];
}
查询
- (BasicUserInfoEntity *)getBasicUserInfo:(NSInteger)userId
{
__block BasicUserInfoEntity *userInfo = [[BasicUserInfoEntity alloc] init];
__weak UserInfoDao *weakSelf = self;
[[UserDaoHelper shareUserHelper].dbQueue inDatabase:^(FMDatabase *db) {
NSString *sql =[NSString stringWithFormat:@"select *from BasicUserInfo where userId = %ld",(long)userId];
FMResultSet *set = [db executeQuery:sql];
while ([set next]) {
userInfo = [weakSelf basicUserInfoWithResultSet:set];
}
}];
return userInfo;
}
- (NSArray *)getBasicUserInfoArray
{
__block NSMutableArray *userArray = nil;
__weak UserInfoDao*weakSelf = self;
[[UserDaoHelper shareUserHelper].dbQueue inDatabase:^(FMDatabase *db) {
NSString *sql = @"select *from BasicUserInfo";
FMResultSet *set = [db executeQuery:sql];
userArray = [NSMutableArray array];
while ([set next]) {
BasicUserInfoEntity *userInfo = [weakSelf basicUserInfoWithResultSet:set];
[userArray addObject:userInfo];
}
}];
return userArray;
}
具体代码以及数据库结构见:https://github.com/jiulin/iOS-FMDBDemo-fmdb-.git
欢迎交流 QQ:983202699