数据储存

iOS开发中数据持久化(四):使用FMDataBase存储数据

2021-01-08  本文已影响0人  落叶兮兮

这篇主要是使用FMDataBase创建简单的数据库表,用来简单的存储数据

Demo地址
对应的实现文件如下:

对应的实现文件

存储成功后的效果图:


数据库结构
对应的数据

(存储的文件是app.db,是一个数据库文件,mac上我是使用DB Browser Fot SQLite进行查看的,非常好用的一个免费软件)

FMDB框架存储数据实际上就是操纵SQLite数据库
首先,新建一个文件Student,继承自NSObject类,在里面定义一些常见的Student属性

@interface Student : NSObject

@property (nonatomic, copy) NSString *id;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *college;//学院
@property (nonatomic, copy) NSString *university;
@property (nonatomic, assign) NSInteger age;

@end

之后,创建一个用于操作数据库的类,所有的关于数据库的操作都封装在里面
命名为DBHelper,继承自NSObject

首先,在存储数据之前,我们需要先判断是否有相应的数据库表,如果没有则创建一个数据库表,如果有,那么直接存储数据

所以,先进行建表操作

定义一些静态常量

static NSString * const dbName = @"app.db";//数据库名称
static FMDatabase *db;//先不使用FMDataBaseQueue,直接使用FMDataBase

static NSString * const kTableName = @"Student";
static NSString * const kColumnID = @"id";
static NSString * const kColumnName = @"name";
static NSString * const kColumnCollege = @"college";
static NSString * const kColumnUniversity = @"university";
static NSString * const kColumnAge = @"age";

创建文件我们使用的第三方框架FCFileManager,数据库使用的FMDB,记得使用cocoapods引入

之后,实现最初的建表操作,在DBHelper中

//数据库路径
+ (NSString *)dbFilePath {
    return [FCFileManager pathForDocumentsDirectoryWithPath:dbName];
}

+ (void)initialize {
    NSLog(@"数据库的存储路径为:%@",[self dbFilePath]);
    db = [FMDatabase databaseWithPath:[self dbFilePath]];
    if (![db open]) {
        NSLog(@"数据库无法开启");
    }
    //创建表
    [self createTable:db];
}

//在数据库中建表
+ (void)createTable:(FMDatabase *)db {
    NSString *createSql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ ("
                           "%@ TEXT,"
                           "%@ TEXT,"
                           "%@ TEXT,"
                           "%@ TEXT,"
                           "%@ INTEGER)",
                           kTableName,
                           kColumnID,
                           kColumnName,
                           kColumnCollege,
                           kColumnUniversity,
                           kColumnAge
                           ];
    BOOL success = [db executeUpdate:createSql];
    if (success) {
        NSLog(@"创建表成功");
    } else {
        NSLog(@"创建表失败");
    }
}

之后,实现相应的数据库操作的方法
这里实现了比较简单的几种操作
1.获取数据库中所有人的名字
2.删除数据操作
3.存储单条数据
4.存储多条数据

在DB.helper.h中声明方法

//获取所有的名字
+ (id)getAllName;

//删除数据
+ (BOOL)delete:(Student *)student;

//将数据存储在FMDataBase中
+ (void)saveObject:(Student *)student;

//存储多条数据进入表中
+ (void)saveObjects:(NSArray *)array;

具体的FMDB的操作建议去阅读作者在github上的说明

获取所有人的名字


````+ (id)getAllName {
    NSString *searchSql = nil;
    FMResultSet *set = nil;
    searchSql = [NSString stringWithFormat:@"SELECT * FROM %@",kTableName];
    set = [db executeQuery:searchSql];
    //执行sql语句,在FMDB中,除了查询语句使用executQuery外,其余的增删改查都使用executeUpdate来实现。
    int i = 0;
    while (set.next) {
        i++;
        NSString *name = [set stringForColumn:@"name"];
        NSLog(@"第%d个名字为:%@",i,name);
    }
    return @[];
}

删除某个对象

+ (BOOL)delete:(Student *)student {
    BOOL success = YES;
    NSString *deleteSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",kTableName,kColumnID];
    BOOL isCan = [db executeUpdate:deleteSql,student.id];
    if (!isCan) {
        success = NO;
        NSLog(@"删除失败");
    } else {
        NSLog(@"删除成功");
    }
    return success;
}

存储单个对象:

+ (void)saveObject:(Student *)student {
    //如果原本已经存在了相同的,则应该将其删除
    [self delete:student];
    NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO %@(%@,%@,%@,%@,%@) VALUES(?,?,?,?,?)",kTableName,kColumnID,kColumnName,kColumnCollege,kColumnUniversity,kColumnAge];
    BOOL success = [db executeUpdate:insertSql,student.id,student.name,student.college,student.university,@(student.age)];
    
    if (success) {
        NSLog(@"插入数据成功");
    } else {
        NSLog(@"插入数据失败");
    }
}

存储多个对象

+ (void)saveObjects:(NSArray *)array {
    if (array.count <= 0) {
        NSLog(@"保存的数据不能为空");
        return;
    }
    for (int i = 0; i < array.count; i++) {
        Student *student = (Student *)[array objectAtIndex:i];
        if (student) {
            [self saveObject:student];
        }
    }
}

之后,在FMDBViewController中初始化数据,添加相应的按钮和点击事件即可
在FMDBViewContrller.h文件中

@property (nonatomic, strong) UIButton *dbSaveButton;
@property (nonatomic, strong) UIButton *dbReadButton;
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) Student *student;

在FMDBViewController.m文件中

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"FMDB存储数据";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.dbSaveButton];
    [self.dbSaveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view);
        make.width.greaterThanOrEqualTo(@0);
        make.height.equalTo(@30);
    }];
    [self.view addSubview:self.dbReadButton];
    [self.dbReadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.dbSaveButton.mas_bottom).offset(20);
        make.width.greaterThanOrEqualTo(@0);
        make.height.equalTo(@30);
    }];
    
    //初始化数据
    [self initStudent];
}

- (void)initStudent {
    self.array = [NSMutableArray array];
    
    Student *student1 = [[Student alloc] init];
    student1.id = @"1234567";
    student1.name = @"落叶兮兮";
    student1.college = @"学院1";
    student1.university = @"大学1";
    student1.age = 23;
    [self.array addObject:student1];
    
    Student *student2 = [[Student alloc] init];
    student2.id = @"1245467767";
    student2.name = @"雪花飞舞";
    student2.college = @"学院1";
    student2.university = @"大学2";
    student2.age = 23;
    [self.array addObject:student2];
}

- (UIButton *)dbSaveButton {
    if (_dbSaveButton) {
        return _dbSaveButton;
    }
    _dbSaveButton = [[UIButton alloc] initWithFrame:CGRectZero];
    _dbSaveButton.titleLabel.font = [UIFont systemFontOfSize:18];
    [_dbSaveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_dbSaveButton setTitle:@"FMDataBase存储数据" forState:UIControlStateNormal];
    [_dbSaveButton addTarget:self action:@selector(fmDataBaseSaveData) forControlEvents:UIControlEventTouchUpInside];
    return _dbSaveButton;
}

- (UIButton *)dbReadButton {
    if (_dbReadButton) {
        return _dbReadButton;
    }
    _dbReadButton = [[UIButton alloc] initWithFrame:CGRectZero];
    _dbReadButton.titleLabel.font = [UIFont systemFontOfSize:18];
    [_dbReadButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_dbReadButton setTitle:@"FMDataBase读取数据" forState:UIControlStateNormal];
    [_dbReadButton addTarget:self action:@selector(fmDataBaseReadData) forControlEvents:UIControlEventTouchUpInside];
    return _dbReadButton;
}

- (void)fmDataBaseSaveData {
    NSLog(@"FMDB存储数据");
    [DBHelper saveObjects:self.array];
}

- (void)fmDataBaseReadData {
    NSLog(@"FMDB读取数据");
    [DBHelper getAllName];
}

运行后就可以在文件app.db中看到我们插入的数据

总结

Demo地址
对应的实现文件如下:

对应的实现文件

存储成功后的效果图:


数据库结构
对应的数据

(存储的文件是app.db,是一个数据库文件,mac上我是使用DB Browser Fot SQLite进行查看的,非常好用的一个免费软件)

iOS开发中数据持久化总结(一);
iOS开发中数据持久化总结(二):NSUserDefault实现数据存储
ios开发中数据持久化总结(三):NSKeyArchive归档解档的实现
ios开发中数据持久化总结(四):使用FMDataBase存储数据

上一篇下一篇

猜你喜欢

热点阅读