.h
@interface FMDBUtil : NSObject
+ (instancetype)ShareDBUtil;
- (void)update:(NSString *)sql values:(NSArray <NSObject *>* _Nullable )values;
- (NSArray<NSObject *> *)select:(NSObject * _Nullable )class sql:(NSString *)sql values:(NSArray <NSObject *>* _Nullable)values;
@end
.m
#import "FMDBUtil.h"
#import <FMDB/FMDB.h>
#import <objc/runtime.h>
@interface FMDBUtil ()
@property (nonatomic, strong) FMDatabaseQueue *dbQueue;
@end
@implementation FMDBUtil
static FMDBUtil *_instance = nil;
+ (instancetype)ShareDBUtil{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[FMDBUtil alloc] init];
});
return _instance;
}
- (instancetype)init{
self = [super init];
if (self) {
self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.sqlite"]];
}
return self;
}
/// 执行增、闪、改
/// @param sql sql语句
/// @param values 填充sql语句的❓
- (void)update:(NSString *)sql values:(NSArray <NSObject *>*)values{
[self.dbQueue inDatabase:^(FMDatabase *db) {
if ([db open]) {
NSError *error = nil;
BOOL result = [db executeUpdate:sql values:values error:&error];
if (!result) {
NSLog(@"%@",error);
}
}
}];
}
/// 查询数据,传className结果集为指定class类型的数组,如果不传className结果集为字典类型的数组
/// @param className 需要查询的模型类名
/// @param sql sql语句
/// @param values 填充sql语句的❓
- (NSArray *)select:(NSString *)className sql:(NSString *)sql values:(NSArray <NSObject *>*)values{
__block NSMutableArray *array = [NSMutableArray array];
[self.dbQueue inDatabase:^(FMDatabase *db) {
if ([db open]) {
NSError *error = nil;
FMResultSet *resultSet = [db executeQuery:sql values:values error:&error];
if (!error) {
while ([resultSet next]) {
NSMutableDictionary *dict = resultSet.columnNameToIndexMap;
if (className.length) {
NSObject *object = [[NSClassFromString(className) alloc] init];
for (int i = 0; i < dict.allKeys.count; i ++) {
NSString *property = dict.allKeys[i];
NSObject *value = [resultSet objectForColumn:property];
if (![value isKindOfClass:[NSNull class]]) {
[object setValue:value forKey:property];
}
}
[array addObject:object];
}else{
NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
for (int i = 0; i < dict.allKeys.count; i ++) {
NSString *property = dict.allKeys[i];
NSObject *value = [resultSet objectForColumn:property];
[resultDict setValue:value forKey:property];
}
[array addObject:resultDict];
}
}
}
}
}];
return array.copy;
}
@end
网友评论