FMDB的使用(增删查改)

FMDB的简单实用,实现了基本的增删查改功能,需要复杂的功能话可以在此基础上进行延伸:
首先建立数据库管理类
DBManager.h文件

#import 

@class TeacherModel;
@class ClassModel;

@interface DBManager : NSObject

/********
*
单例 数据库管理
*
********/
+ (DBManager *) sharedDBManager;

/***
 *
 添加老师
 *
 ***/
- (void) addTeachder:(TeacherModel *) teacher;

/***
 *
 删除老师
 *
 ***/
- (void) deleteTeachder:(TeacherModel *) teacher;

/***
 *
 查找老师
 *
 ***/
- (TeacherModel *) searchTeacher:(TeacherModel *) teacher;
/***
 *
 更改老师信息
 *
 ***/
- (void) updateTeachder:(TeacherModel *) teachder;

/***
 *
 打印所有老师信息
 *
 ***/
- (NSMutableArray *) getAllTeacher;


DBManager.m文件

#import "DBManager.h"
#import "FMDB.h"
#import "TeacherModel.h"
#import "ClassModel.h"

static DBManager *dbManager = nil;

@interface DBManager(){
    
    FMDatabase *_db;
}


@end


@implementation DBManager

+ (DBManager *)sharedDBManager {

//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        dbManager = [[DBManager alloc] init];
//        [dbManager initDataBase];
//    });
//    
    if (dbManager == nil) {
        dbManager = [[DBManager alloc] init];
        [dbManager initDataBase];
    }
   
    return dbManager;
    
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    
    if (dbManager == nil) {
        
        dbManager = [super allocWithZone:zone];
        
    }
    
    return dbManager;
    
}

-(id)copy{
    return self;
}

-(id)mutableCopy{
    return self;
}

-(id)copyWithZone:(NSZone *)zone{
    return self;
}

-(id)mutableCopyWithZone:(NSZone *)zone{
    return self;
}


//初始化数据库
- (void) initDataBase {
//document路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//文件路径
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"teacher.sqlite"];
//初始化FMDB对象
    _db = [FMDatabase databaseWithPath:filePath];
//对数据库进行操作 打开
    [_db open];
//初始化数据表
    NSString *teacherSql = @"CREATE TABLE 'teacher' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL,'teacher_id' VARCHAR(255),'teacher_name' VARCHAR(255),'teacher_age' VARCHAR(255),'teacher_sex' VARCHAR(255))";
//创建数据表
    [_db executeUpdate:teacherSql];
//关闭数据库
    [_db close];
}


//添加老师
- (void)addTeachder:(TeacherModel *)teacher {
    [_db open];
    
    NSInteger mark = 0;
    FMResultSet *result = [_db executeQuery:@"SELECT * FROM teacher"];
    
    while ([result next]) {
        if (mark < [[result stringForColumn:@"teacher_id"] integerValue]) {
            mark = [[result stringForColumn:@"teacher_id"] integerValue];
        }
    }
    mark++;
    [_db executeUpdate:@"INSERT INTO teacher(teacher_id,teacher_name,teacher_age,teacher_sex)VALUES(?,?,?,?)",@(mark),teacher.name,@(teacher.age),teacher.sex];
    
    [_db close];
}

//删除老师
- (void)deleteTeachder:(TeacherModel *)teacher {
    
    [_db open];
    [_db executeUpdate:@"DELETE FROM teacher where teacher_id = ?",teacher.ID];
    
    [_db close];
}

- (TeacherModel *) searchTeacher:(TeacherModel *) teacher {
    [_db open];
    
    FMResultSet *result = [_db executeQuery:@"SELECT * FROM teacher"];
    TeacherModel *tempTeacher;
    while ([result next]) {
        tempTeacher = [[TeacherModel alloc] init];
        if ([teacher.name isEqualToString:@"HD"]) {
            tempTeacher = teacher;
        }
    }
    [_db close];
    
    return tempTeacher;
}


- (void)updateTeachder:(TeacherModel *)teachder {
    [_db open];
    
    [_db executeUpdate:@"UPDATE 'teacher' SET teacher_name = ? where teacher_id = ?",teachder.name,teachder.ID];
     [_db executeUpdate:@"UPDATE 'teacher' SET teacher_age = ? where teacher_id = ?",@(teachder.age),teachder.ID];
     [_db executeUpdate:@"UPDATE 'teacher' SET teacher_sex = ? where teacher_id = ?",teachder.sex,teachder.ID];
    
    [_db close];
}

- (NSMutableArray *)getAllTeacher{
    
    [_db open];
    NSMutableArray *dataArray = [NSMutableArray array];
    FMResultSet *result = [_db executeQuery:@"SELECT * FROM teacher"];
    
    while ([result next]) {
        TeacherModel *teacher = [[TeacherModel alloc] init];
        teacher.ID = @([[result stringForColumn:@"teacher_id"] integerValue]);
        teacher.name = [result stringForColumn:@"teacher_name"];
        teacher.age = [[result stringForColumn:@"teacher_age"] intValue];
        teacher.sex = [result stringForColumn:@"teacher_sex"];
        [dataArray addObject:teacher];
        
    }
    [_db close];
    
    return dataArray;
    
}

使用

#import "FMDBViewController.h"
#import "DBManager.h"
#import "TeacherModel.h"

@interface FMDBViewController ()
@property (strong, nonatomic)  UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;


@end

@implementation FMDBViewController

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addTeacher)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"查询" style:UIBarButtonItemStylePlain target:self action:@selector(listTeacher)];
    
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataArray = [[DBManager sharedDBManager] getAllTeacher];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    TeacherModel *teacher = self.dataArray[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@---%@---%d",teacher.name,teacher.sex,teacher.age];
    
    return cell;
}

//设置删除按钮
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        TeacherModel *teacher = self.dataArray[indexPath.row];
        [[DBManager sharedDBManager] deleteTeachder:teacher];
        [self.dataArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:0];
        [self.tableView reloadData];
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TeacherModel *teacher = self.dataArray[indexPath.row];
    teacher.age++;
    [[DBManager sharedDBManager] updateTeachder:teacher];
    self.dataArray = [[DBManager sharedDBManager] getAllTeacher];
    [self.tableView reloadData];
    
}

- (void) addTeacher {
    
    TeacherModel *teacher = [[TeacherModel alloc] init];
    teacher.name = @"HD";
    teacher.age = 18;
    teacher.sex = @"girl";
    
    [[DBManager sharedDBManager] addTeachder:teacher];
    self.dataArray = [[DBManager sharedDBManager] getAllTeacher];
    [self.tableView reloadData];
    
    
}

- (void) listTeacher {
    
    self.dataArray = [[DBManager sharedDBManager] getAllTeacher];
    for (TeacherModel *teacher in self.dataArray) {
        if ([teacher.name isEqualToString:@"HD"]) {
            NSLog(@"----teacher----- %@",teacher.name);
        }
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

你可能感兴趣的:(FMDB的使用(增删查改))