介绍下本人,工作一年多了,但是感觉也就是菜鸟一个。前些天项目用到数据库,打算用FMDB,之前用过但是也没有及时总结。上网搜了搜FMDB的工具类,也没找到。今天事儿少,就献丑一下,把自己的代码贴上来。
先上.h
#import <Foundation/Foundation.h>
#import "FMDB.h"
@class EOANotificationModel;
@interface FMDataBaseHelper : NSObject
//得到数据库的路径
- (NSString *)getDBPath;
//获取表中数据,组成一个数组
- (NSArray *)getData:(NSString *)sqlStr;
//查询表中一共有多少条数据
- (int)numOfRows:(NSString *)str;
// 插入模型数据
+ (BOOL)insertModal:(EOANotificationModel *)modal;
/** 查询数据,如果 传空 默认会查询表中所有数据 */
+ (NSArray *)queryData:(NSString *)querySql;
/** 删除数据,如果 传空 默认会删除表中所有数据 */
- (BOOL)deleteData:(NSString *)deleteSql;
/** 修改数据 */
+ (BOOL)modifyData:(NSString *)modifySql;
@property(nonatomic,retain) FMDB *db;
@end
再上.m
#import "FMDataBaseHelper.h"
#import "FMDatabaseAdditions.h"
@implementation FMDataBaseHelper
- (id)init
{
self = [super init];
if (self) {
NSString *filePath = [self getDBPath];
self.db = [FMDatabase databaseWithPath:filePath];
[self.db open];
}
return self;
}
- (NSString *)getDBPath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"Notification.db"];
return dbPath;
}
- (NSArray *)getData:(NSString *)sqlStr{
NSMutableArray *array = [[[NSMutableArray alloc] init]autorelease];
FMResultSet *rs = [self.db executeQuery:sqlStr];
while ([rs next]) {
NSData *data = [rs dataForColumn:@"Data"];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
[array addObject:dic];
}
[rs close];
return array;
}
- (BOOL)deleteData:(NSString *)deleteSql{
BOOL operaResult = [self.db executeUpdate:deleteSql];
return operaResult;
}
- (int)numOfRows:(NSString *)str{
return [self.db intForQuery:str];
}
- (void)dealloc{
[self.db release];
[super dealloc];
}
@end
代码很简单,勿喷,提供给有需要的人。第一次写博客,以后有时间也会不定时的写一些总结 。
转载于:https://www.cnblogs.com/risehao/p/4482557.html
