iOS数据持久化--FMDB简单使用
2018-04-26 本文已影响38人
ghost__
基础认识:FMDB是一个轻量级的针对iOS数据库操作的SDK,在iOS中操作的是SQLite数据库
使用目的:需要进行大批量的数据读写
正题
1.三大主要类
FMDatabase : sql语句的执行
FMResultSet:查询结果集
FMDatabaseQueue:多线程安全访问,
2.数据库安全队列创建 同时也是创建了数据库
FMDatabaseQueue *dbQueue = [FMDatabaseQueue databaseQueueWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"dbName.db"]];
3.创建数据库表
[dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
if ([db open]) {
NSString *sql = @"creat table if not exists tableName(colunmn1 varchar(255),colunmn2 varchar(255))";
BOOL result = [db executeUpdate:sql];
NSLog(@"%@",result ? @"创建表成功" : @"创建表失败");
// [db close];
}
}];
4.插入数据
[dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
if ([db open]) {
NSString *sql = @"INSERT INTO tableName VALUES('message','message')";
BOOL result = [db executeUpdate:sql];
NSLog(@"%@",result ? @"插入数据成功" : @"插入数据失败");
[db close];
}
}];
5.查询所有数据
NSString *sql = @"select *from tableName";
NSMutableArray *allDatas = [NSMutableArray array];
[dbQueue inDatabase:^(FMDatabase *db) {
if ([db open]) {
FMResultSet *set = [db executeQuery:sql];
while ([set next]) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *columnName in columnNames) {
NSString *columnData = [set stringForColumn:columnName];
[dict setValue:columnData forKey:columnName];
}
[allDatas addObject:dict];
}
[db close];
}
}];
//allDatas 表中所有数据
6.删除所有数据
NSString *sql = @"delete from tableName";
[self.dbQueue inDatabase:^(FMDatabase *db) {
if ([db open]) {
BOOL result = [db executeUpdate:sql];
NSLog(@"%@",result ? @"删除数据成功" : @"删除数据失败");
[db close];
}
}];
7.判断指定表是否存在
__block BOOL isTabelExist = NO;
[self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
if ([db open]) {
FMResultSet *rs = [db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tableName];
while ([rs next]) {
NSInteger count = [rs intForColumn:@"count"];
isTabelExist = count == 0 ? NO : YES;
}
[db close];
}
}];
8.更新数据与事务处理
[dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
if ([db open]) {
NSString *sql = @"update model set one = 'newMessage' where two = 'twoMessage'";
BOOL result = [db executeUpdate:sql];
if (!result) {
//当最后*rollback的值为YES的时候,事务回退,如果最后*rollback为NO,事务提交
*rollback = YES;
return;
}
}
}];
关于spl的更多知识:http://www.runoob.com/sql/sql-tutorial.html
小demo:https://github.com/DeepSeaGhost/FMDBDemo