iOS——FMDB的简单使用

什么是FMDB

最近在实现一个简单APP的收藏功能,需要用到数据库,将数据存储到本地,但在iOS中使用C语言函数对原生SQLite数据库进行增删改查操作,是比较麻烦的,FMDB是一个针对libsqlite3框架进行封装的第三方库,它使用OC封装了c语言的API,使用起来比较方便。

FMDB的主要类型

FMDatabase:一个FMDatabase对象代表一个单独的SQLite数据库,通过SQLite语句执行数据库的增删改查操作
FMResultSet:使用FMDatabase对象查询数据库后的结果集
FMDatabaseQueue:用于多线程操作数据库,它保证线程安全

如何使用FMDB

导入库

和其他的第三库一样,我们需要将FMDB导入到工程,这里我使用的是CocoaPod导入,这个在之前的博客中有介绍过如何导入,iOS——Masonry的简单使用,只需要将其中的pod 'Masonry',改成pod 'FMDB'即可。
如果要使用多个第三方库,直接加入pod ‘FMDB’。

platform:ios,'9.0'
target '知乎日报' do
pod 'JSONModel'
pod 'Masonry'
pod 'SDWebImage'
pod 'MJRefresh'
pod 'FMDB'
end


最后cd 到文件目录下,输入 pod install.这样就导入了。

简单步骤

1.首先导入头文件

#import "FMDB.h"

2.创建数据库属性,以及你想导入数据库的属性

@interface HomeController ()

@property (nonatomic, strong) FMDatabase *db;
// 数据库路径
@property (nonatomic, strong) NSString* dbPath;

// 设置数据库存储的数据
@property (nonatomic, strong) NSString* titleString;
@property (nonatomic, strong) NSString* imageUrlString;
@property (nonatomic, strong) NSString* webViewString;
// 标记数据是否被找到
@property (nonatomic, assign) int ans;

@end

3.创建数据库

// 创建数据库
- (void)getDatabase {
    //获得数据库文件的路径
    NSString* doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString* fileName=[doc stringByAppendingPathComponent:@"HotDog.sqlite"];
    self.dbPath = fileName;
    // 获取数据库
    FMDatabase* testDatebase = [FMDatabase databaseWithPath:self.dbPath];
    // 打开数据库
    if ([testDatebase open]) {
        // 创表
        // 表中名字是你存储数据的名字
        // 下面的表存储了收藏界面的文字数据,图片的下载地址,以及webView的下载地址
        BOOL result = [testDatebase executeUpdate:@"CREATE TABLE IF NOT EXISTS t_agreeOrder (id integer PRIMARY KEY AUTOINCREMENT, titleString text NOT NULL, imageUrlString text NOT NULL, webString text NOT NULL);"];
        if (result) {
            NSLog(@"创表成功");
        } else {
            NSLog(@"创表失败");
        }
    }
    self.db = testDatebase;
    
}

[doc stringByAppendingPathComponent:@“HotDog.sqlite”] 后面的字符串就是数据库的名字,当这个数据库不存在是,系统会自动创建,如果存在时,那么下次就可以根据这个名字打开这个数据库
这里有一个创建表的操作,个人理解为在数据中规定数据类型,相当于一个索引,可以根据这个名字去访问这个类型的数据。
下面就可以进行对表的一些操作了。

增删查改

这里是我在项目中的一些应用,使用背景:点击收藏按钮,如果数据不在数据库,那么插入数据库,如果数据以及在数据库,那么相当于取消收藏,就去删除数据库中的数据。
1.首先根据滚动视图的位置更新需要插入的属性。

// 更新收藏数据
- (void) repalceData:(UIScrollView *)scrollView {
    int page = scrollView.contentOffset.x / WIDTH;
    _titleString = [_titleArray[page] title];
    StoriesModel *story = _titleArray[page];
    _imageUrlString = story.images[0];
    _webViewString = _webViewArray[page];
//    NSLog(@"%@ %@ 777%@", _titleString, _imageUrlString, _webViewString);
}

2.查询数据库中是否存在数据

// 查询数据
- (void) queryData {
    FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
    if ([db open]) {
        // 1.执行查询语句
        FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM t_agreeOrder"];
        _ans = 0;
        // 2.遍历结果
        while ([resultSet next]) {
            NSString* testString = [resultSet stringForColumn:@"titleString"];
            NSLog(@"%@11", testString);
            if ([testString isEqual:_titleString]) {
                _ans = 1;
                break;
            }
        }
            [db close];
        }
}

NSString* testString = [resultSet stringForColumn:@"titleString"];这句话就是根据我们当时创表的索引名去获得对应的数据。
3.插入数据

//插入数据
-(void)insert {
    FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
    if ([db open]) {
     // 向表中插入符合要求的数据
     BOOL res = [self.db executeUpdate:@"INSERT INTO t_agreeOrder (titleString, imageUrlString, webString) VALUES (?, ?, ?);", _titleString, _imageUrlString, _webViewString];

    if (!res) {
        NSLog(@"增加数据失败");
    } else{
        NSLog(@"增加数据成功");
    }
      [db close];
    }
}

[self.db executeUpdate:@"INSERT INTO t_agreeOrder (titleString, imageUrlString, webString) VALUES (?, ?, ?);", _titleString, _imageUrlString, _webViewString];: 这里的括号中的对应的为表中的索引,插入的值就是我们后面定义的一些属性。
4.删除数据

// 删除数据
- (void)deleteData {
    FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
    if ([db open]) {
        NSString *sql = @"delete from 't_agreeOrder' where titleString = ?";
        BOOL res = [self.db executeUpdate:sql, _titleString];
        NSString *secondSql = @"delete from 't_agreeOrder' where imageUrlString = ?";
        BOOL res1 = [self.db executeUpdate:secondSql, _imageUrlString];
        NSString *thirdSql = @"delete from 't_agreeOrder' where webString = ?";
        BOOL res2 = [self.db executeUpdate:thirdSql, _webViewString];
        if (!res || !res1 || !res2) {
            NSLog(@"数据删除失败");
        } else {
            NSLog(@"数据删除成功");
        }
        [db close];
    }
}

NSString *sql = @"delete from 't_agreeOrder' where titleString = ?"; BOOL res = [self.db executeUpdate:sql, _titleString];: 当where titleString = ?条件成立时,表中指定元素。

5.更新数据

// 更新数据
- (void)updateData {
FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
    if ([db open]) {
        NSString *sql = @"UPDATE t_agreeOrder SET id = ? WHERE  titleString = ?";
        BOOL res = [db executeUpdate:sql, @"1", @"修改数据"];
        if (!res) {
            NSLog(@"数据修改失败");
        } else {
            NSLog(@"数据修改失败");
            [self queryData];
        }
        [db close];
    }
}

@"UPDATE t_agreeOrder SET id = ? WHERE titleString = ?":id是这类类型的索引,当后面的条件成立时修改。

简单就了解了这么一部分,后面再次使用或者深入学习时,继续补充。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>