在很多时候,我们会用到数据库,我们移动端使用的数据库,一般都是嵌入型数据库,是一种较轻型的数据库,
一般很多时候,大牛封装的FMDB的第三方,已经足够满足我们的需求了!
现在分享一下自己的学习心得,希望能帮到大家!
一、简要说明
1.什么是FMDB
FMDB是IOS平台的SQLite数据库框架
FMDB是以OC的方式封装了SQLite的C语言API
2.FMDB的优点
使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码
对比苹果自带的Coredata框架,更加的轻量级和灵活
提供了多线程安全的数据库操作方法,有效地防止数据混乱
3.FMDB的github地址
二、核心类
FMDB有三个主要的类
(1)FMDatabase
一个FMDatabase对象就代表一个单独的SQLite数据库
用来执行SQL语句
(2)FMResultSet
使用FMDatabase执行查询后的结果集
(3)FMDatabaseQueue
用于在多线程中执行多个查询或更新,它是线程安全的
三、FMDB使用步骤
下载FMDB文件,并将FMDB文件夹添加到项目中去(也可使用cocoapods导入)
libsqlite3.0框架,导入头文件FMDatabase.h
代码实现,与SQLite使用步骤相似,创建数据库路径,获得数据库路径,打开数据库,然后对
数据库进行增、删、改、查操作,最后关闭数据库。
创建FMDatabase对象是参数为SQLite数据库文件路径,该路径可以是一下三种方式之一
文件路径,该文件路径无需真实存在,如果不存在会自动创建
空字符串(@“”)。表示会在临时目录创建一个空的数据库,当FMDatabase连接关闭时,文件也会被删除
NULL。将创建一个内在数据库,同样的,当FMDatabase连接关闭时,数据将会被销毁
我自己使用的数据模型:
@property(nonatomic,assign)int ID;//id
@property(nonatomic,strong)NSString *name;//name
@property(nonatomic,strong)NSString *age;//age
我自己使用的工具类:
.h
#import <Foundation/Foundation.h>
@interface DataBaseTools : NSObject
//创建一个单例类
+(instancetype)sharedManager;
//初始化数据库
-(void)initDataBase;
//插入数据
-(void)insert;
//删除数据
-(void)deletesWithByids:(NSString *)ida;
//查询数据
-(NSMutableArray *)queryWithByids:(int)ida;
//彻底销毁的操作
-(void)allRemovesDatas;
@end
.m
#import "DataBaseTools.h"
#import "FMDB.h"
#import "FMDatabase.h"
#import "FMModel.h"
FMDatabase *__db = nil;
@implementation DataBaseTools
//创建一个单例类
+(instancetype)sharedManager
{
static DataBaseTools *dataBase = nil;
static dispatch_once_t once_Token;
dispatch_once(&once_Token ,^{
dataBase = [[self alloc]init];
});
return dataBase;
}
//初始化数据库
-(void)initDataBase
{
//获取数据库文件路径 不一定真实,也可以为空,如果为空就创建
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *fileName = [doc stringByAppendingPathComponent:@"student.sqlite"];
//获得数据库
FMDatabase *db = [FMDatabase databaseWithPath:fileName];
//打开数据库
if ([db open]) {
//有就打开,没有就创建
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(@"创建失败");
}
__db = db;
}
}
//插入数据
-(void)insert
{
for (int i = 0; i<10; i++) {
NSString *names = [NSString stringWithFormat:@"h_Jack%d",arc4random_uniform(50)];
//不确定的参数用?来占位
[__db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);",names,@(arc4random_uniform(50))];
}
}
//删除数据
-(void)deletesWithByids:(NSString *)ida
{
//删除固定的一个数值
// NSString *nameStr = @"h_Jack35";
[__db executeUpdate:@"delete from t_student where name = ?;",ida];
// [__db executeUpdate:@"delete from t_student where age = ?;",ida];
}
//查询数据
-(NSMutableArray *)queryWithByids:(int)ida
{
//执行查询语句--查询整个表
FMResultSet *resultSet = [__db executeQuery:@"select * from t_student"];
//根据条件查询
FMResultSet *resultSets = [__db executeQuery:@"select * from t_student where id > ?",[NSString stringWithFormat:@"%d",ida]];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
//遍历结果
while ([resultSets next]) {
FMModel *model = [FMModel new];
model.ID = [resultSets intForColumn:@"id"];
model.name = [resultSets stringForColumn:@"name"];
model.age = [resultSets stringForColumn:@"age"];
[array addObject:model];
}
[resultSets close];
return array;
}
//彻底销毁的操作
-(void)allRemovesDatas
{
//如果表格存在,则销毁
[__db executeUpdate:@"drop table if exists t_student"];
}
上面的操作增、删、改、查都有,
四、在tableview里面展示插入的数据,然后我做了一个左滑删除的操作,具体代码如下:
//添加
-(void)insertClick
{
[[DataBaseTools sharedManager] insert];
}
//查找
-(void)insertsClick
{
self.oneArray = [[DataBaseTools sharedManager] queryWithByids:[TF1.text intValue]];
[self.tableView reloadData];
NSLog(@"--array is %@",self.oneArray);
}
-(void)creatTableView
{
self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 300, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.tableFooterView = [[UIView alloc]init];
[self.tableView registerNib:[UINib nibWithNibName:@"FmCell" bundle:nil] forCellReuseIdentifier:@"FmCell"];
[self.view addSubview:self.tableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.oneArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FmCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FmCell"forIndexPath:indexPath];;
FMModel *model = self.oneArray[indexPath.row];
cell.IDlab.text = [NSString stringWithFormat:@"%d",model.ID];
cell.nameLab.text = model.name;
cell.ageLab.text = model.age;
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"删除";
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0) __TVOS_PROHIBITED
{
UITableViewRowAction* deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//这里面写点击按钮的所响应的事件
FMModel *model = self.oneArray[indexPath.row];
NSLog(@"----%@--%ld",model.name,indexPath.row);
[[DataBaseTools sharedManager] deletesWithByids:model.name];
[self.oneArray removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView reloadData];
}];
deleteAction.backgroundColor = [UIColor redColor];
return @[deleteAction];
}
最终效果图如下:
左滑删除后,数据直接从数据库里面删除!
作者:稻草人11223