FMDB封装使用,写成工具类

直接上代码

//
//  DataBaseTool.h
//  TheDasBest
//
//  Created by  on 16/7/25.
//  Copyright © 2016年. All rights reserved.
//

#import 
#import "FMDB.h"
@interface DataBaseTool : NSObject
+(FMDatabase*)shareDataBase;
+(BOOL)openDataBase;
+(BOOL)closeDataBase;
@end
//
//  DataBaseTool.m
//  TheDasBest
//
//  Created by  on 16/7/25.
//  Copyright © 2016年 . All rights reserved.
//

#import "DataBaseTool.h"
static FMDatabase*_db;
@implementation DataBaseTool
//创建数据库对象
+(FMDatabase*)shareDataBase
{
//    if ([self copyDBFile])
//    {
        if (_db==nil)
        {
            _db=[[FMDatabase alloc]initWithPath:[self getDBFilePath ]];
        }
        //设置缓存,提高效率
        [_db setShouldCacheStatements:YES];

//    }
//    else
//    {
//        NSAssert(NO, @"数据库拷贝失败");
//    }
    return _db;
}

//文件路径
+(NSString*)getDBFilePath
{
    NSString *documentPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"cosmetics.sqlite"];
    NSLog(@"文件路径是:%@",dbFilePath);
    return dbFilePath;
}

//打开数据库
+(BOOL)openDataBase
{
    if ([_db open]==NO)
    {
        [_db close];
        NSAssert(NO, @"数据库打开失败!");
        
    }
    [_db setShouldCacheStatements:YES]
    ;
    return YES;
}
+(BOOL)closeDataBase
{
    if ([_db close]==NO)
    {
        NSAssert(NO, @"关闭数据库失败");
    }
    return  YES;
}
@end

//
//  groupDao.h
//  TheDasBest
//
//  Created by  on 16/7/25.
//  Copyright © 2016年 . All rights reserved.
//

#import 

@interface groupDao : NSObject
+(NSArray*)queryAllGroup;//声明

@end
//
//  groupDao.m
//  TheDasBest
//
//  Created by ** on 16/7/25.
//  Copyright © 2016年** . All rights reserved.
//

#import "groupDao.h"
#import "DataBaseTool.h"
#import "groupTable.h"
@implementation groupDao
//查询所有的数据
+(NSArray*)queryAllGroup
{
    FMDatabase*db=[DataBaseTool shareDataBase];
    [DataBaseTool openDataBase];
    NSMutableArray *arr = [NSMutableArray array];

    if ([db tableExists:@"groupTable"])
    {
        //查询
        FMResultSet*set=[db executeQuery:@"select *from groupTable"];
        while ([set next])
        {
            groupTable*model=[[groupTable alloc]init];
           // model.id=[set intForColumn:@"id"];
            model.name=[set stringForColumn:@"name"];
            model.kind=[set stringForColumn:@"kind"];
            model.number=[set intForColumn:@"number"];
            [arr addObject:model];
        }
    }
    [DataBaseTool closeDataBase];
    return arr;

}
@end

你可能感兴趣的:(FMDB封装使用,写成工具类)