数据库DBManger实现cell的增删改查

数据库的增删改查 DBManger文件


再用到的时候只需要改Model的名字,以及对应的变量即可,使用方法在下一篇文章


`#import 
``#import "ReadModel.h"
``@interface DBManager : NSObject
+(DBManager *)defaultManager;
//插入数据
- (void)insertDataModel:(ReadModel *)model;
//查询数据
 - (BOOL)isHasDataIDFromTable:(NSString *)dataId;
//删除数据
- (void)deleteNameFromTable:(NSString *)dataId;
//查询所有
- (NSArray *)getData;
@end`

#import "DBManager.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"

@implementation DBManager
{
FMDatabase * _dataBase;

}
static DBManager * manager=nil;
+(DBManager *)defaultManager
{
//只调用一次,保证线程安全
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
    if(manager==nil){
        manager=[[DBManager alloc]init];
    
    }
});

return manager;
}

- (instancetype)init
{
 if(self=[super init]){

    
    NSString * path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/selectInfor.db"];
    

    //很据路径创建表
    _dataBase = [[FMDatabase alloc]initWithPath:path];
    
    //如果创建成功 打开
    if ([_dataBase open]) {
        //create table if not exists 固定写法
        //selectInfo 表的名字
        NSString * createSql = @"create table if not exists selectInfo( id varchar(1024),title varchar(1024),pic varchar(1024),createtime varchar(1024), author varchar(1024))";
        //createSql = @"create table if not exists selectInfo(id integer primary key autoincrement not null,class varchar(1024) data glob)";
        
        //integer 数字  varchar字符串 glob 二进制数据NSData
        if ([_dataBase executeUpdate:createSql]){//executeUpdate 返回值是BOOL
            //executeUpdate 增、删、改、创建 都是使用这个方法
            NSLog(@"创建成功");
        }else{
            NSLog(@"%@",[_dataBase lastErrorMessage]);
        }
    }

}
return self;
}

//插入
- (void)insertDataModel:(ReadModel *)model{

NSString * insertSql = @"insert into selectInfo(id,title,pic,createtime,author) values(?,?,?,?,?)";

BOOL success=[_dataBase executeUpdate:insertSql,model.dataID,model.title,model.pic,model.createtime,model.author];

if (!success) {
    NSLog(@"%@",[_dataBase lastErrorMessage]);
}else{
    NSLog(@"插入成功");
}

}
//查找
 - (BOOL)isHasDataIDFromTable:(NSString *)dataId
{

NSString * isSql = @"select *from selectInfo where id=?";

//FMResultSet 查询结果的集合类
FMResultSet * set = [_dataBase executeQuery:isSql,dataId];
//[set next] 查找当前行 找到继续中查找下一行
if ([set next]) {
    return YES;
}else{
    return NO;
}
return [set next];//next 返回时一个BOOL
}
//删除
- (void)deleteNameFromTable:(NSString *)dataId
{

NSString * deleteSql = @"delete from selectInfo where id=?";
if ([_dataBase executeUpdate:deleteSql,dataId]) {
    NSLog(@"删除成功");
}

}
- (NSArray *)getData{

NSString *resultSql = @"select *from selectInfo";

FMResultSet * set = [_dataBase executeQuery:resultSql];
NSMutableArray * arr = [NSMutableArray array];

while ([set next]) {
  ReadModel* model = [[ReadModel alloc]init];
    model.dataID = [set stringForColumn:@"id"];
    model.title = [set stringForColumn:@"title"];
    model.pic=[set stringForColumn:@"pic"];
    model.createtime=[set stringForColumn:@"createtime"];
    model.author=[set stringForColumn:@"author"];
    [arr addObject:model];
}
return arr;
}


@end

按钮,以及点击实现收藏


//收藏按钮
UIButton * collectButton = [FactoryUI createButtonWithFrame:CGRectMake(SCREEN_W - 50, 80, 40, 40) title:nil titleColor:nil imageName:@"iconfont-iconfontshoucang" backgroundImageName:nil target:self selector:@selector(collectButtonClick:)];
[collectButton setImage:[UIImage imageNamed:@"iconfont-iconfontshoucang-2"] forState:UIControlStateSelected];
collectButton.tag = 10;
[self.view addSubview:collectButton];

#pragma mark - 按钮响应函数
//收藏
-(void)collectButtonClick:(UIButton *)button
{
button.selected = YES;
DBManager * manager = [DBManager defaultManager];
if ([manager isHasDataIDFromTable:self.readModel.dataID])
{
    //说明已经收藏过
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已经收藏过" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
    
    //iOS9更新之后的提示框
//        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请不要重复收藏" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction * action1 =  [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//        [alert addAction:action1];
//        [self presentViewController:alert animated:YES completion:nil];
}
else
{
    //未曾收藏过,则插入一条数据
    [manager insertDataModel:self.readModel];
    
}
}

从数据库读取收藏的内容


#pragma mark - 从数据库读取数据
-(void)loadData
{
DBManager * manager = [DBManager defaultManager];
NSArray * array =[manager getData];
self.dataArray = [NSMutableArray arrayWithArray:array];
[_tableView reloadData];
}

实现cell的删除的处理


//设置编辑cell的类型
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
//设置cell可编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
//删除的思路:1.先删除数据库中的数据,2.然后删除界面的cell,3.最后刷新界面
DBManager * manager = [DBManager defaultManager];
ReadModel * model = self.dataArray[indexPath.row];
[manager deleteNameFromTable:model.dataID];

//删除cell
[self.dataArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

//刷新界面
//[_tableView reloadData];
}

你可能感兴趣的:(数据库DBManger实现cell的增删改查)