iOS sqlite 增删改查 简单封装(基于 FMDB)

时间:2022-05-24 06:15:17

/**
 *  对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查
 *
 *  基于 FMDB
 *
 *  操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整体进行操作
 *
 *  根据 model 对象自动建表,字段类型只支持 NSString , NSIteger , float
 *
 *  用到 runtime 运行时获取 model 属性
 *
 */

 //
// AGDatabaseManager.h
//
// Created by Ager on 15/11/10.
// Copyright © 2015年 Ager. All rights reserved.
// /**
* 对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查
*
* 基于 FMDB
*
* 操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整体进行操作
*
* 根据 model 对象自动建表,字段类型只支持 NSString , NSIteger , float
*
* 用到 runtime 运行时获取 model 属性
*
*/ #import <Foundation/Foundation.h> @interface AGDatabaseManager : NSObject + (AGDatabaseManager*)shareAGDatabaseManager; /**
* 创建表格
*
* @param cls model 类
* @param tbName 表名
* @param keyName 主键字段
* @param key 主键的属性设置
*
* @return 创建表格是否成功
*/
- (BOOL)creatTable:(Class)cls tableName:(NSString*)tbName keyName:(NSString*)keyName primaryKey:(NSString*) key; /**
* 向表格插入数据
*
* @param model 数据模型与数据库表格对应
* @param tbName 要操作的表名
*
* @return 添加是否成功
*/
- (BOOL)insert:(id)model tableName:(NSString*)tbName; /**
* 更新数据
*
* @param tbName 要操作的表名
* @param model 数据模型与数据库表格对应
* @param str 更新操作查要更新的数据的条件
*
* @return 更新是否成功
*/
- (BOOL)update:(id)model tableName:(NSString*)tbName where:(NSString*)str; /**
* 删除数据
*
* @param tbName 要删除数据的表名
* @param str 要删除的数据的查找条件
*
* @return 删除是否成功
*/
- (BOOL)deleteTableName:(NSString*)tbName where:(NSString*)str; /**
* 查询数据
*
* @param model 数据模型与数据库表格对应
* @param tbName 要操作的表名
* @param str 删除操作查要删除的数据的条件
*
* @return 查询结果 (数组每一项为字典)
*/
- (NSArray*)select:(Class)model tableName:(NSString*)tbName where:(NSString*)str; /**
* 查询全部数据
*
* @param model 数据模型与数据库表格对应
* @param tbName 要操作的表名
*
* @return 查询结果 (数组每一项为字典)
*/
- (NSArray*)selectALL:(Class)model tableName:(NSString*)tbName; @end

AGDatabaseManager.h

 //
// AGDatabaseManager.m
//
// Created by Ager on 15/11/10.
// Copyright © 2015年 Ager. All rights reserved.
// #import "AGDatabaseManager.h"
#import "FMDatabase.h"
#import <objc/runtime.h> static FMDatabase *fmdb = nil; @implementation AGDatabaseManager - (instancetype)init{
if (self = [super init]) { static dispatch_once_t oneToken;
dispatch_once(&oneToken, ^{
NSString *document = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[];
NSString *filePath = [document stringByAppendingPathComponent:@"database.sqlite"];
NSLog(@"%@",document);
fmdb = [FMDatabase databaseWithPath:filePath]; });
}
return self;
} + (AGDatabaseManager*)shareAGDatabaseManager{
return [[AGDatabaseManager alloc]init];
} - (BOOL)creatTable:(Class)cls tableName:(NSString*)tbName keyName:(NSString*)keyName primaryKey:(NSString*) key{ NSArray *array = [self getModelAllProperty:cls];
NSMutableString *sql = [NSMutableString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (",tbName]; for (int i = ; i < array.count; i++) {
NSDictionary *dic = array[i];
[sql appendFormat:@"%@ %@ ",[dic objectForKey:@"name"],[dic objectForKey:@"type"]];
if(keyName != nil && [keyName isEqualToString:[dic objectForKey:@"name"]]){
[sql appendString:key];
}
if (i < array.count - ){
[sql appendString:@","];
}
} [sql appendString:@")"]; NSLog(@"创建表格: %@",sql); [fmdb open];
BOOL result = [fmdb executeUpdate:[sql copy]];
NSLog(@"创建表格:%@",result ? @"成功":@"失败");
[fmdb close];
return result;
} - (BOOL)insert:(id)model tableName:(NSString*)tbName{ NSArray *array = [self getModelAllProperty:[model class]]; NSMutableString *propertyStr = [[NSMutableString alloc]init];
NSMutableString *valuesStr = [[NSMutableString alloc]init]; for (int i = ; i < array.count; i++) {
NSDictionary *dic = array[i];
[propertyStr appendString:[dic objectForKey:@"name"]];
[valuesStr appendFormat:@"'%@'",[model valueForKey:[dic objectForKey:@"name"]]]; if (i < array.count - ){
[propertyStr appendString:@","];
[valuesStr appendString:@","];
}
}
NSMutableString *sql = [NSMutableString stringWithFormat:@"INSERT INTO %@ (%@) values (%@)",tbName,propertyStr ,valuesStr];
NSLog(@"添加数据 : %@",sql);
[fmdb open];
BOOL result = [fmdb executeUpdate:[sql copy]];
[fmdb close];
NSLog(@"添加数据:%@",result ? @"成功":@"失败"); return result;
} - (BOOL)update:(id)model tableName:(NSString*)tbName where:(NSString*)str{
NSArray *array = [self getModelAllProperty:[model class]];
NSMutableString *sql = [NSMutableString stringWithFormat:@"UPDATE %@ SET ",tbName]; for (int i = ; i < array.count; i++) {
NSDictionary *dic = array[i];
NSString *pro = [dic objectForKey:@"name"];
[sql appendFormat:@"%@ = '%@'",pro,[model valueForKey:pro]];
if (i < array.count - ){
[sql appendString:@","];
}
} [sql appendFormat:@" where %@",str]; NSLog(@"修改数据 : %@",sql);
[fmdb open];
BOOL result = [fmdb executeUpdate:[sql copy]];
[fmdb close];
NSLog(@"更新数据:%@",result ? @"成功":@"失败");
return result;
} - (BOOL)deleteTableName:(NSString*)tbName where:(NSString*)str{
NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@",tbName,str];
NSLog(@"删除数据 : %@",sql);
[fmdb open];
BOOL result = [fmdb executeUpdate:sql];
[fmdb close];
NSLog(@"更新数据:%@",result ? @"成功":@"失败");
return result;
} - (NSArray*)select:(Class)model tableName:(NSString*)tbName where:(NSString*)str{
NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@",tbName,str];
NSArray *array = [self getModelAllProperty:[model class]];
[fmdb open];
NSLog(@"查询数据 : %@",sql);
FMResultSet *set = [fmdb executeQuery:sql];
NSMutableArray *allArray = [[NSMutableArray alloc]init];
while ([set next]) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for (int i = ; i < array.count; i++) {
NSDictionary *dic1 = array[i];
NSString *pro = [dic1 objectForKey:@"name"];
[dic setValue:[set stringForColumn:pro] forKey:pro];
}
[allArray addObject:dic];
} [set close];
[fmdb close];
return [allArray copy];
} - (NSArray*)selectALL:(Class)model tableName:(NSString*)tbName {
NSString *sql = [NSString stringWithFormat:@"select * from %@ ",tbName];
NSArray *array = [self getModelAllProperty:[model class]];
[fmdb open];
NSLog(@"查询数据 : %@",sql);
FMResultSet *set = [fmdb executeQuery:sql];
NSMutableArray *allArray = [[NSMutableArray alloc]init];
while ([set next]) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for (int i = ; i < array.count; i++) {
NSDictionary *dic1 = array[i];
NSString *pro = [dic1 objectForKey:@"name"];
[dic setValue:[set stringForColumn:pro] forKey:pro];
}
[allArray addObject:dic];
} [set close];
[fmdb close];
return [allArray copy];
} #pragma mark --- 辅助方法 --- /**
* 获取 model 类全部的属性和属性类型
*
* @param cls model 类 class
*
* @return 返回 model 的属性和属性类型
*/
- (NSArray *)getModelAllProperty:(Class)cls{ unsigned int count = ;
objc_property_t *propertys = class_copyPropertyList(cls, &count);
NSMutableArray *array = [NSMutableArray array];
for (int i = ; i < count; i++) { objc_property_t property = propertys[i];
NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; NSString *type = [self getPropertyAttributeValue:property name:@"T"]; if ([type isEqualToString:@"q"]||[type isEqualToString:@"i"]) {
type = @"INTEGER";
}else if([type isEqualToString:@"f"] || [type isEqualToString:@"d"]){
type = @"FLOAT";
}else{
type = @"TEXT";
} NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:propertyName , @"name",type , @"type", nil]; [array addObject:dic]; }
free(propertys); return array.copy;
} /**
* 获取属性的特征值
*/ - (NSString*)getPropertyAttributeValue:(objc_property_t) pro name:(NSString*)name{ unsigned int count = ;
objc_property_attribute_t *attributes = property_copyAttributeList(pro, &count); for (int i = ; i < count; i++) {
objc_property_attribute_t attribute = attributes[i];
if (strcmp(attribute.name, name.UTF8String) == ) {
return [NSString stringWithCString:attribute.value encoding:NSUTF8StringEncoding];
}
}
free(attributes);
return nil;
} @end

AGDatabaseManager.m

FMDB + AGDatabaseManager 文件