标签:
源码如下,只有一个类文件
// // DBHelper.h // // Created by Jason_Msbaby on 15/10/15. // Copyright ? 2015年 张杰. All rights reserved. // /** * 简单封装了对于sqlite的使用 没有加入对事务及其他复杂的特性 基于传入sql语句的方式进行执行 使用单例模式 根据model对象自动创建表 只支持 NSInter NSString float 数据类型的支持 默认增加 id自增主键 默认采用单数据库模式 默认数据库名字为databse.sqlite */ #import <Foundation/Foundation.h> @interface DBHelper : NSObject /** * 创建单例对象 * * @return 返回本类实例 */ +(instancetype)defaultManger; /** * 创建数据表 * * @param sql sql语句 * * @return 返回 创建是否成功的标识 */ -(BOOL)creatTabel:(NSString*)sql; /** * 使用实体类型进行自动建表 * * @param tableName 表名称 * @param modelType 实体类型 用于自动检索实体的属性 * * @return 返回bool */ -(BOOL)createTabel:(NSString*)tableName modelType:(Class)modelType; /** * 增删改语句通用执行方法 * * @param sql 传入sql语句 * * @return 返回bool值 */ -(BOOL)execute:(NSString*)sql; /** * 执行查询 * * @param sql 传入sql语句 * * @return 返回 数组<字典> 字典的键与数据库字段名相同 */ -(NSMutableArray*)executeQuery:(NSString*)sql; /** * 插入一个实体对象到某一张表 * * @param model 实体对象 * @param tableName 表名 * * @return 返回bool值 */ -(BOOL)insertModel:(id)model TableName:(NSString *)tableName; @end
// // DBHelper.m // douBan // // Created by Jason_Msbaby on 15/10/15. // Copyright ? 2015年 张杰. All rights reserved. // #import <objc/runtime.h> #import "DBHelper.h" #import <sqlite3.h> #define CachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] #define DataBaseName @"database.sqlite" @implementation DBHelper static DBHelper *dbhelper; static sqlite3 *sql3; //********************************************* 具体实现部分 ***************************************// +(instancetype)defaultManger{ if (dbhelper == nil) { dbhelper = [DBHelper new]; } return dbhelper; } -(BOOL)creatTabel:(NSString *)sql{ return [self execute:sql]; } -(BOOL)createTabel:(NSString *)tableName modelType:(Class)modelType{ NSMutableString *sql = [NSMutableString stringWithFormat:@"CREATE TABLE IF NOT EXISTS ‘%@‘ (‘id‘ INTEGER PRIMARY KEY AUTOINCREMENT,",tableName]; NSArray *names =[NSArray arrayWithArray:[self allPropertyNameInClass:modelType]]; for (NSDictionary *dic in names) { NSString *name = dic[@"name"]; NSString *type = dic[@"type"]; [sql appendString:[NSString stringWithFormat:@"‘%@‘ %@ ,",name,type]]; } NSString *realSql = [sql substringToIndex:sql.length-1]; realSql = [realSql stringByAppendingString:@");"]; NSLog(@"%@",realSql); return [self execute:realSql]; } -(BOOL)execute:(NSString *)sql{ [self open]; int res = sqlite3_exec(sql3, sql.UTF8String, NULL, NULL, NULL); [self close]; return !res; } -(NSMutableArray *)executeQuery:(NSString *)sql{ [self open]; sqlite3_stmt *stmt = nil; NSMutableArray *arr = [NSMutableArray array]; int res = sqlite3_prepare(sql3, sql.UTF8String, -1, &stmt, NULL); if (res == SQLITE_OK) { while (sqlite3_step(stmt) == SQLITE_ROW) { int count = sqlite3_column_count(stmt); NSMutableDictionary *dic = [NSMutableDictionary dictionary]; for (int i = 0; i < count; i++) { const char *columName = sqlite3_column_name(stmt, i); const char *value = (const char*)sqlite3_column_text(stmt, i); if (value!=NULL) { NSString *columValue =[NSString stringWithUTF8String:value]; [dic setObject:columValue forKey:[NSString stringWithUTF8String:columName]]; }else{ [dic setObject:@"" forKey:[NSString stringWithUTF8String:columName]]; } } [arr addObject:dic]; } sqlite3_finalize(stmt); [self close]; return arr; }else{ return nil; } return nil; } -(BOOL)insertModel:(id)model TableName:(NSString *)tableName{ NSDictionary *dic = [self DictionaryFromModel:model]; NSMutableString *keys = [NSMutableString string]; NSMutableString *values = [NSMutableString string]; for (int i = 0; i < dic.count; i++) { NSString *key = dic.allKeys[i]; NSString *value = dic.allValues[i]; [keys appendFormat:@"%@,",key]; [values appendFormat:@"‘%@‘,",value]; } NSString *sql = [NSString stringWithFormat:@"insert into %@(%@) values(%@)",tableName,[keys substringToIndex:keys.length -1],[values substringToIndex:values.length - 1]]; NSLog(@"%@",sql); return ![self execute:sql]; } //********************************************* 本类辅助函数 ***************************************// -(BOOL)open{ NSString *fileName = [CachePath stringByAppendingPathComponent:DataBaseName]; NSLog(@"path=%@",fileName); return !sqlite3_open(fileName.UTF8String, &sql3); } -(BOOL)close{ return !sqlite3_close(sql3); } //字典与对象的转换函数 //对象转换为字典 -(NSDictionary*)DictionaryFromModel:(id)model{ NSMutableDictionary *dic = [NSMutableDictionary dictionary]; Class modelClass = object_getClass(model); unsigned int count = 0; objc_property_t *pros = class_copyPropertyList(modelClass, &count); for (int i = 0; i < count; i++) { objc_property_t pro = pros[i]; NSString *name = [NSString stringWithFormat:@"%s", property_getName(pro)] ; id value = [model valueForKey:name]; if (value !=nil) { [dic setObject:value forKey:name]; } } free(pros); return dic; } //********************************************* 属性动态解析部分 ***************************************// //Runtime辅助函数解析类的属性特征等行为 //获取属性的特征值 -(NSString*)attrValueWithName:(NSString*)name InProperty:(objc_property_t)pro{ unsigned int count = 0; objc_property_attribute_t *attrs = property_copyAttributeList(pro, &count); for (int i = 0; i < count; i++) { objc_property_attribute_t attr = attrs[i]; if (strcmp(attr.name, name.UTF8String) == 0) { return [NSString stringWithUTF8String:attr.value]; } } free(attrs); return nil; } //获取属性的值 -(id)valueOfproperty:(objc_property_t)pro cls:(Class)cls{ Ivar ivar = class_getInstanceVariable(cls, [self attrValueWithName:@"V" InProperty:pro].UTF8String); return object_getIvar(cls, ivar); } //获取类的所有属性名称与类型 -(NSArray *)allPropertyNameInClass:(Class)cls{ NSMutableArray *arr = [NSMutableArray array]; unsigned int count; objc_property_t *pros = class_copyPropertyList(cls, &count); for (int i = 0; i < count; i++) { NSString *name =[NSString stringWithFormat:@"%s",property_getName(pros[i])]; NSString *type = [self attrValueWithName:@"T" InProperty:pros[i]]; //类型转换 if ([type isEqualToString:@"q"]||[type isEqualToString:@"i"]) { type = @"INTEGER"; }else if([type isEqualToString:@"f"] || [type isEqualToString:@"d"]){ type = @"REAL"; }else{ type = @"TEXT"; } NSDictionary *dic = @{@"name":name,@"type":type}; [arr addObject:dic]; } free(pros); return arr; } @end
简单封装sqlite3 实现实体对象与关系型数据库的相关操作【IOS】
标签:
原文地址:http://my.oschina.net/zhangjie9142/blog/517783