iOS FMDB使用与缓存数据

96
iOS_成才录
0.7 2015.11.12 19:28* 字数 373

一、FMDB简介

  • 什么是FMDB
    • FMDB是iOS平台SQLite数据库 框架
    • FMDB以面向OC的方式封装了SQLite的C语言API
  • FMDB优点

    • 使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码
    • 对比苹果自带的Core Data框架,更加轻量级和灵活
    • 提供了多线程安全的数据库操作方法,有效地防止数据混乱
  • FMDB的github地址

  • 核心类

    • FMDatabase
    • 一个FMDatabase对象就代表一个单独的SQLite数据库
    • 用来执行SQL语句
    • FMDatabase这个类是线程不安全的,如果在多个线程中同时使用一个FMDatabase实例,会造成数据混乱等问题
    • 为了保证线程安全,FMDB提供方便快捷的FMDatabaseQueue类
    • FMResultSet
    • 使用FMDatabase执行查询后的结果集
    • FMDatabaseQueue
    • 用于在多线程中执行多个查询或更新,它是线程安全的
// FMDatabaseQueue的创建
FMDatabaseQueue *queue = 

[FMDatabaseQueue databaseQueueWithPath:path];
[queue inDatabase:^(FMDatabase*db) {
   [db executeUpdate:@"INSERTINTO t_student(name)VALUES (?)",@"Jack"];
   [db executeUpdate:@"INSERTINTO t_student(name)VALUES (?)",@"Rose"];
   [db executeUpdate:@"INSERTINTO t_student(name)VALUES (?)",@"Jim"];
   
   FMResultSet*rs= [dbexecuteQuery:@"select* from t_student"];
   while([rsnext]) {
        // …
   }
}];
    ```

+ 注意:打开数据库,文件路径有三种情况
    - 具体文件路径:如果不存在会自动创建
    - 空字符串@"":会在临时目录创建一个空的数据库,当FMDatabase连接关闭时,数据库文件也被删除‘ 
    - nil:会创建一个内存中临时数据库,当FMDatabase连接关闭时,数据库会被销毁

  ```objc
// 通过指定SQLite数据库文件路径来创建FMDatabase对象
FMDatabase*db= [FMDatabase databaseWithPath:path];
if (![dbopen]) {
   NSLog(@"数据库打开失败!");
}
  • 在FMDB中,除查询以外的所有操作,都称为“更新”:create、drop、insert、update、delete等
// 使用executeUpdate:方法执行更新
- (BOOL)executeUpdate:(NSString*)sql, ...
- (BOOL)executeUpdateWithFormat:(NSString*)format,...
- (BOOL)executeUpdate:(NSString*)sqlwithArgumentsInArray:(NSArray*)arguments
  • 执行查询
- (FMResultSet*)executeQuery:(NSString*)sql, ...
- (FMResultSet*)executeQueryWithFormat:(NSString*)format,...
- (FMResultSet*)executeQuery:(NSString*)sqlwithArgumentsInArray:(NSArray*)arguments

二、CoreData 与 FMDB

  • coreData:自动生成SQL语句,不能自己设置,个性化的、优化的等SQL语句不能实现
  • FMDB:可以自己定制不同的SQL语句,扩展性好

三、FMDB实例 基本使用

  • 1.导入FMDB框架到项目中
  • 2.使用FMDB


# 二、增删改查
+ 数据库操作都放在queue中的,queue中操作database,线程是安全的

```objc
#import "JPViewController.h"
#import "FMDB.h"

@interface JPViewController ()
@property (nonatomic, strong) FMDatabase *db;
@end

@implementation JPViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"students.sqlite"];
    
    // 2.得到数据库
    FMDatabase *db = [FMDatabase databaseWithPath:filename];
    
    // 3.打开数据库
    if ([db open]) {
        // 4.创表
        BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"];
        if (result) {
            NSLog(@"成功创表");
        } else {
            NSLog(@"创表失败");
        }
    }
    
    self.db = db;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self delete];
    [self insert];
    [self query];
}

- (void)insert
{
    for (int i = 0; i<10; i++) {
        NSString *name = [NSString stringWithFormat:@"jack-%d", arc4random_uniform(100)];
        // executeUpdate : 不确定的参数用?来占位,参数都必须是对象
        [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);", name, @(arc4random_uniform(40))];
//        [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);" withArgumentsInArray:@[name, @(arc4random_uniform(40))]]; // ?方式,参数要是对象,不是对象要包装为对象
        
        // executeUpdateWithFormat : format方式拼接,不确定的参数用%@、%d等来占位
//        [self.db executeUpdateWithFormat:@"INSERT INTO t_student (name, age) VALUES (%@, %d);", name, arc4random_uniform(40)];
// 注意:如果直接写%@不用加单引号两边,会自动加单引号两边,如果'jack_%d'的两边不加单引号就会报错,所以要注意
     [self.db executeUpdateWithFormat:@"INSERT INTO t_student (name, age) VALUES ('jack_%d', %d);", name, arc4random_uniform(40)]; 
    }
}

- (void)delete
{
//    [self.db executeUpdate:@"DELETE FROM t_student;"];
    [self.db executeUpdate:@"DROP TABLE IF EXISTS t_student;"];
    [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"];
}

- (void)query
{
    // 1.执行查询语句
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM t_student"];
    
    // 2.遍历结果
    while ([resultSet next]) {
        int ID = [resultSet intForColumn:@"id"];
        NSString *name = [resultSet stringForColumn:@"name"];
        int age = [resultSet intForColumn:@"age"];
        NSLog(@"%d %@ %d", ID, name, age);
    }
}
@end
+  事务操作

```objc
#import "JPViewController.h"
#import "FMDB.h" // 导入头文件

@interface JPViewController ()
@property (nonatomic, strong) FMDatabaseQueue *queue;
@end

@implementation JPViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"persons.sqlite"];
    
    // 2.得到数据库
    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:filename];
    
    // 3.打开数据库
    [queue inDatabase:^(FMDatabase *db) {
        // 4.创表
        BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_person (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"];
        if (result) {
            NSLog(@"成功创表");
        } else {
            NSLog(@"创表失败");
        }
    }];
    
    self.queue = queue;
}

// 事务操作:错误会回滚
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//    [self.queue inDatabase:^(FMDatabase *db) {
//        [db beginTransaction];
//        
//        [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);", @"jake", @30];
//        [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);", @"jake", @30];
//        [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);", @"jake", @30];
//        [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);", @"jake", @30];
//        
//        [db commit];
//    }];
    
//    [self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
//        [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);", @"jake", @30];
//        [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);", @"jake", @30];
//        [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);", @"jake", @30];
//        [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);", @"jake", @30];
//    }];
    
  
}
@end

四、FMDB缓存数据

#import "JPStatusTool.h"
#import "JPHttpTool.h"
#import "MJExtension.h"
#import "FMDB.h"
#import "JPStatus.h"

@implementation JPStatusTool

/** 数据库实例 */
static FMDatabase *_db;

+ (void)initialize
{
    // 1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"status.sqlite"];
    
    // 2.得到数据库
    _db = [FMDatabase databaseWithPath:filename];
    
    // 3.打开数据库
    if ([_db open]) {
        // 4.创表
        BOOL result = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_home_status (id integer PRIMARY KEY AUTOINCREMENT, access_token text NOT NULL, status_idstr text NOT NULL, status_dict blob NOT NULL);"];
        if (result) {
            NSLog(@"成功创表");
        } else {
            NSLog(@"创表失败");
        }
    }
}

+ (void)homeStatusesWithParam:(JPHomeStatusesParam *)param success:(void (^)(JPHomeStatusesResult *))success failure:(void (^)(NSError *))failure
{
//    param.count = @5;
    
    // 从数据库中读取(加载)缓存数据(微博模型数组)
    NSArray *cachedHomeStatuses = [self cachedHomeStatusesWithParam:param];
    if (cachedHomeStatuses.count != 0) { // 有缓存数据
        if (success) {
            JPHomeStatusesResult *result = [[JPHomeStatusesResult alloc] init];
            result.statuses = cachedHomeStatuses;
            success(result);
        }
    } else { // 没有缓存数据
        NSDictionary *params = [param keyValues];
        
        [JPHttpTool get:@"https://api.weibo.com/2/statuses/home_timeline.json" params:params success:^(id responseObj) {
            // 新浪返回的字典数组
            NSArray *statusDictArray = responseObj[@"statuses"];
            
            // 缓存微博字典数组
            [self saveHomeStatusDictArray:statusDictArray accessToken:param.access_token];
            
            if (success) {
                JPHomeStatusesResult *result = [JPHomeStatusesResult objectWithKeyValues:responseObj];
                success(result);
            }
        } failure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    }
}

/**
 *  通过请求参数去数据库中加载对应的微博数据
 *
 *  @param param 请求参数
 */
+ (NSArray *)cachedHomeStatusesWithParam:(JPHomeStatusesParam *)param
{
    // 创建数组缓存微博数据
    NSMutableArray *statuses = [NSMutableArray array];
    
    // 根据请求参数查询数据
    FMResultSet *resultSet = nil;
    if (param.since_id) {
        resultSet = [_db executeQuery:@"SELECT * FROM t_home_status WHERE access_token = ? AND status_idstr > ? ORDER BY status_idstr DESC limit ?;", param.access_token, param.since_id, param.count];
    } else if (param.max_id) {
        resultSet = [_db executeQuery:@"SELECT * FROM t_home_status WHERE access_token = ? AND status_idstr <= ? ORDER BY status_idstr DESC limit ?;", param.access_token, param.max_id, param.count];
    } else {
        resultSet = [_db executeQuery:@"SELECT * FROM t_home_status WHERE access_token = ? ORDER BY status_idstr DESC limit ?;", param.access_token, param.count];
    }
    
    // 遍历查询结果
    while (resultSet.next) {
        NSData *statusDictData = [resultSet objectForColumnName:@"status_dict"];
        NSDictionary *statusDict = [NSKeyedUnarchiver unarchiveObjectWithData:statusDictData];
        // 字典转模型
        JPStatus *status = [JPStatus objectWithKeyValues:statusDict];
        // 添加模型到数组中
        [statuses addObject:status];
    }
    
    return statuses;
}

/**
 *  缓存微博字典数组到数据库中
 */
+ (void)saveHomeStatusDictArray:(NSArray *)statusDictArray accessToken:(NSString *)accessToken
{
    for (NSDictionary *statusDict in statusDictArray) {
        // 把statusDict字典对象序列化成NSData二进制数据
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:statusDict];
        [_db executeUpdate:@"INSERT INTO t_home_status (access_token, status_idstr, status_dict) VALUES (?, ?, ?);",
         accessToken, statusDict[@"idstr"], data];
    }
}
@end
数据存储