对FMDB进行进一步的封装,不用在写SQL相对应的语句.
//例如需要出入的数据:(数组存储的是对应model类型)获取所有的数据
[[WDadaBasesharedDataBase]addNews:self.modelArraywithMoel:[[DynamicModelalloc]init]];
//获取所有的数据
self.modelArray = [[WDadaBasesharedDataBase]getAllNews:[[DynamicModelalloc] init]];
//
// WDadaBase.h
// FMDB的使用
//
#import <Foundation/Foundation.h>
#import "DynamicModel.h"
@interface WDadaBase : NSObject
+ (instancetype)sharedDataBase;
#pragma mark - 新闻列表
//- (void)addNews:(DynamicModel *)dynamicModel;
- (void)addNews:(NSArray *)models withMoel:(id)model;
//- (void)updateNews:(DynamicModel *)dynamicModel;
- (NSMutableArray *)getAllNews:(id)model;
//- (void)CreateNewTable:(DynamicModel *)dynamicModel;
//- (void)selecetDataWith:(DynamicModel *)dynamicModel;
- (NSArray *)getAllProperties:(id)model;
- (NSDictionary *)allProperties:(id)model;
- (NSArray *)getAllPropertiesTypeAttribute:(id)model;
@end
//
// WDadaBase.m
// FMDB的使用
#import "WDadaBase.h"
#import "FMDB.h"
#import <objc/runtime.h>
#define NotNullString(x) ((x) ? (x) : (@""))
@interface WDadaBase()
@property(nonatomic,strong)FMDatabase *db;
@end
@implementation WDadaBase
static WDadaBase *singleton = nil;
+(instancetype)sharedDataBase{
staticdispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleton = [[WDadaBasealloc] init];
// [singleton createTableWithName:table_name];
// [singleton createTableWithName:@"tab_Subnews"];
});
returnsingleton;
}
-(void)createTableWithName:(NSString *)name{
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
documentsPath = [documentsPath stringByAppendingPathComponent:@"test2.sqlite"];
_db = [FMDatabasedatabaseWithPath:documentsPath];
if ([_dbopen]) {
NSLog(@"打开成功");
}else{
NSLog(@"打开失败");
}
if ([_dbtableExists:name])
{
[_dbclose];
return;
}
// 初始化数据表
// NSString *newsSql3 = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (id integer PRIMARY KEY AUTOINCREMENT,'cellTitle' VARCHAR(255),'source' VARCHAR(255),'imageUrl' VARCHAR(255),'newsUrl' VARCHAR(255),'newsID'VARCHAR(255),imageData blob)",name];
NSArray *properties = [selfgetAllProperties:[[DynamicModelalloc] init]];
NSArray *Attributes = [selfgetAllPropertiesTypeAttribute:[[DynamicModelalloc] init]];
// 1.创建表语句头部拼接
NSString *creatTableStrHeader = [NSStringstringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (id integer PRIMARY KEY AUTOINCREMENT",name];
NSString *creatTableStrMiddle =[NSStringstring];
if (properties.count == Attributes.count) {
for (int i =0; i <properties.count; i++) {
NSString *typeStr=@"TEXT";
if ([Attributes[i]isEqualToString:@"NSData"]) {
typeStr=@"BLOB";
}
creatTableStrMiddle = [creatTableStrMiddle stringByAppendingFormat:@",%@ %@",[propertiesobjectAtIndex:i],typeStr];
}
// 3.创建表语句尾部拼接
NSString *creatTableStrTail =[NSStringstringWithFormat:@")"];
// 4.整句创建表语句拼接
NSString *newsSql = [NSStringstring];
newsSql = [newsSql stringByAppendingFormat:@"%@%@%@",creatTableStrHeader,creatTableStrMiddle,creatTableStrTail];
if ([_dbexecuteUpdate:newsSql]) {
NSLog(@"newsSql成功");
}else{
NSLog(@"newsSql失败");
}
}
[_db close];
}
//- (void)addNews:(DynamicModel *)dynamicModel{
//
// if (!_db) {
// [self createTableWithName:@"DynamicModel"];
//
// }
// [_db open];
//
// NSString *sql = [NSString stringWithFormat:@"INSERT INTO DynamicModel(cellTitle,source,imageUrl,newsUrl,newsID,imageData)VALUES('%@','%@','%@','%@','%@',?)",dynamicModel.cellTitle,dynamicModel.source,dynamicModel.imageUrl,dynamicModel.newsUrl,dynamicModel.newsID];
//
// if ([_db executeUpdate:sql,dynamicModel.imageData]) {
// NSLog(@"charu成功");
//
// }else{
// NSLog(@"charu失败");
//
// }
//
//[_db executeUpdate:@"INSERT INTO news(cellTitle,source,imageUrl,newsUrl,newsID,imageData)VALUES(?,?,?,?,?,?)",dynamicModel.cellTitle,dynamicModel.source,dynamicModel.imageUrl,dynamicModel.newsUrl,dynamicModel.newsID,dynamicModel.imageData]
//
// [_db close];
//}
- (void)addNews:(NSArray *)models withMoel:(id)model{
NSString *className = [NSStringstringWithUTF8String:object_getClassName(model)];
if (!_db) {
[selfcreateTableWithName:className];
}
[_db open];
NSArray *properties = [selfgetAllProperties:model];
NSString *modelStr = [NSStringstring];
NSString *modelValueStr = [NSStringstring];
for (int i =0; i<properties.count; i++) {
NSString *property = properties[i];
modelStr = [modelStr stringByAppendingString:property];
modelValueStr = [modelValueStr stringByAppendingString:@"?"];
if (i< properties.count -1) {
modelStr = [modelStr stringByAppendingString:@","];
modelValueStr = [modelValueStr stringByAppendingString:@","];
}
}
for (NSInteger i=0 ;i < models.count;i++) {
id obj = models[i];
NSMutableArray *modelPropertyArray = [NSMutableArrayarray];
for (int j =0; j<properties.count; j++) {
id values = [objvalueForKey:[properties objectAtIndex:j]];
// if (values == nil) {
// values = @"";
// }
NSLog(@"j= %d,properties = %@,value = %@",j,[propertiesobjectAtIndex:j],values);
[modelPropertyArray addObject:NotNullString(values)];
}
NSString *sql = [NSStringstringWithFormat:@"INSERT INTO %@(%@)VALUES(%@)",className,modelStr,modelValueStr];
if ([_dbexecuteUpdate:sql values:modelPropertyArray error:nil]) {
NSLog(@"插入的数据成功");
}else{
NSLog(@"插入的数据失败");
}
}
[_db close];
}
- (NSMutableArray *)getAllNews:(id)model{
NSString *className = [NSStringstringWithUTF8String:object_getClassName(model)];
if (!_db) {
[selfcreateTableWithName:className];
}
[_db open];
NSMutableArray *dataArray = [[NSMutableArrayalloc] init];
NSString * sqlStr = [NSStringstringWithFormat:@"SELECT * FROM %@",className];
FMResultSet *res = [_dbexecuteQuery:sqlStr];
while ([resnext]) {
NSArray *properties = [selfgetAllProperties:model];
NSArray *attributes = [selfgetAllPropertiesTypeAttribute:[[DynamicModelalloc] init]];
id modelobj = [[[modelclass] alloc]init];
// for (NSString *property in properties) {
//
// if ([property containsString:@"Data"]) {
// [modelobj setValue:[res dataForColumn:property] forKey:property];
//
// }else{
//
//
// [modelobj setValue:[res stringForColumn:property] forKey:property];
// }
//
//
// }
for (int i =0; i< properties.count; i++) {
NSString *property = properties[i];
if ([attributes[i]isEqualToString:@"NSData"]) {
[modelobj setValue:[resdataForColumn:property] forKey:property];
}else{
[modelobj setValue:[resstringForColumn:property]forKey:property];
}
}
// DynamicModel *model = [[DynamicModel alloc] init];
//
// model.cellTitle = [res stringForColumn:@"cellTitle"];
// model.source = [res stringForColumn:@"source"];
// model.imageUrl = [res stringForColumn:@"imageUrl"];
// model.newsUrl = [res stringForColumn:@"newsUrl"];
// model.newsID = [res stringForColumn:@"newsID"];
// NSData * data = [res dataForColumn:@"imageData"];
// model.imageData = data;
[dataArray addObject:modelobj];
}
[_db close];
return dataArray;
}
// - (void)deleteNews:(DynamicModel *)dynamicModel {
// [_db open];
//
// [_db executeUpdate:@"DELETE FROM news WHERE newsID = ?",dynamicModel.newsID];
//
// [_db close];
// }
// - (void)updateNews:(DynamicModel *)dynamicModel {
//
// if (!_db) {
// [self createTableWithName:@"DynamicModel"];
//
// }
// [_db open];
//
// UIImage *image = [UIImage imageNamed:@"premium.PNG"];
// NSData *imageData = UIImagePNGRepresentation(image);
// model.imageData = imageData;
// [_db executeUpdate:@"UPDATE 'news' SET cellTitle = ? WHERE newsID = ? ",@"修改的名称",dynamicModel.newsID];
//
// [_db executeUpdate:@"UPDATE 'news' SET imageData = ? WHERE newsID = ? ",imageData,dynamicModel.newsID];
// [_db executeUpdate:@"UPDATE 'news' SET imageData = ? ,cellTitle = ? WHERE newsID = ? ",imageData,dynamicModel.newsID];
// if ([_db executeUpdate:@"UPDATE 'DynamicModel' SET imageData = ? ,cellTitle = ? WHERE newsID = ? ",imageData,@"修改的名字",dynamicModel.newsID]) {
// NSLog(@"更新成功");
// }else{
// NSLog(@"更新失败");
// }
//
// [_db close];
// }
//- (void)CreateNewTable:(DynamicModel *)dynamicModel{
//
// [_db open];
//
//
// if ([_db executeUpdate:@"INSERT INTO tests2 select * FROM news"]) {
// NSLog(@"tests2成功");
// }else{
// NSLog(@"tests2失败");
// }
//
// if (isTableExist(_db, @"tests2")) {
// NSLog(@"cunai");
// }else{
// NSLog(@"bucunai");
//
//
// }
//
// [_db close];
//
//}
#pragma mark---查询数字库存在的表
BOOL isTableExist(FMDatabase *db,NSString * tableName)
{
FMResultSet *rs2 = [dbexecuteQuery:@"select name from sqlite_master where type='table' order by name;"];
while ([rs2next])
{
NSString * columnName = [rs2stringForColumnIndex:0];
NSLog(@"isTableOK ---%@",columnName);
}
FMResultSet *rs = [dbexecuteQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tableName];
while ([rsnext])
{
// just print out what we've got in a number of formats.
NSInteger count = [rsintForColumn:@"count"];
NSLog(@"isTableOK %ld", (long)count);
if (0 == count)
{
returnNO;
}
else
{
returnYES;
}
}
returnNO;
}
#pragma mark---查询数据库表中的数据
//- (void)selecetDataWith:(DynamicModel *)dynamicModel {
//
// [_db open];
// NSString *sqlStr = [NSString stringWithFormat:@"SELECT news.cellTitle, news.newsID, tab_Subnews.cellTitle ,tab_Subnews.newsID FROM news INNER JOIN tab_Subnews ON news.newsID = tab_Subnews.newsID ORDER BY news.cellTitle"];
// NSString *sqlStr = [NSString stringWithFormat:@"SELECT tab_Subnews.cellTitle ,tab_Subnews.newsID FROM news INNER JOIN tab_Subnews ON news.newsID = tab_Subnews.newsID"];
//
// FMResultSet *res = [_db executeQuery:sqlStr];
// while ([res next]) {
// DynamicModel *model = [[DynamicModel alloc] init];
// model.cellTitle = [res stringForColumn:@"cellTitle"];
// model.source = [res stringForColumn:@"source"];
// model.imageUrl = [res stringForColumn:@"imageUrl"];
// model.newsUrl = [res stringForColumn:@"newsUrl"];
// model.newsID = [res stringForColumn:@"newsID"];
// NSData * data = [res dataForColumn:@"imageData"];
// model.imageData = data;
// for (NSInteger i= 0 ;i<2;i++) {
//
//
// NSString *str = [res stringForColumnIndex:i];
// NSLog(@"str=%@",str);
//
// }
// }
//
// [_db close];
//}
- (NSArray *)getAllProperties:(id)model
{
u_int count;
objc_property_t *properties =class_copyPropertyList([modelclass], &count);
NSMutableArray *propertiesArray = [NSMutableArrayarray];
for (int i =0; i < count ; i++)
{
constchar* propertyName = property_getName(properties[i]);
[propertiesArray addObject: [NSStringstringWithUTF8String: propertyName]];
}
free(properties);
// NSLog(@"反射机制获取的----数组中的元素为----%@",propertiesArray);
return propertiesArray;
}
//获取所有属性的类型可返回数组或者字典
- (NSArray *)getAllPropertiesTypeAttribute:(id)model
{
u_int count;
objc_property_t *properties =class_copyPropertyList([modelclass], &count);
NSMutableArray *propertiesArray = [NSMutableArrayarray];
for (int i =0; i < count; i++) {
objc_property_t property = properties[i];
// const char *name = property_getName(property);
// NSString *propertyName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
constchar * type = property_getAttributes(property);
// NSString *attr = [NSString stringWithCString:type encoding:NSUTF8StringEncoding];
NSString *typeString = [NSStringstringWithUTF8String:type];
NSArray * attributes = [typeStringcomponentsSeparatedByString:@","];
NSString * typeAttribute = [attributesobjectAtIndex:0];
NSString * propertyType = [typeAttributesubstringFromIndex:1];
constchar * rawPropertyType = [propertyTypeUTF8String];
if (strcmp(rawPropertyType,@encode(float)) ==0) {
//it's a float
NSLog(@"float");
} elseif (strcmp(rawPropertyType,@encode(int)) ==0) {
//it's an int
NSLog(@"int");
} elseif (strcmp(rawPropertyType,@encode(id)) ==0) {
//it's some sort of object
NSLog(@"id");
} else {
NSLog(@"other");
// According to Apples Documentation you can determine the corresponding encoding values
}
if ([typeAttributehasPrefix:@"T@"] && [typeAttributelength] > 1) {
NSString * typeClassName = [typeAttributesubstringWithRange:NSMakeRange(3, [typeAttributelength]-4)]; //turns @"NSDate" into NSDate
Class typeClass = NSClassFromString(typeClassName);
if (typeClass !=nil) {
[propertiesArray addObject:typeClassName];
// Here is the corresponding class even for nil values
}
}
}
free(properties);
// NSLog(@"反射机制获取的----数组中的元素为----%@",propertiesArray);
return propertiesArray;
}
//动态获取一个自定义类对象中的所有属性
- (NSDictionary *)allProperties:(id)model
{
NSMutableDictionary *props = [NSMutableDictionarydictionary];
unsignedint outCount, i;
objc_property_t *properties =class_copyPropertyList([modelclass], &outCount);
for (i =0; i<outCount; i++)
{
objc_property_t property = properties[i];
constchar *char_f =property_getName(property);
NSString *propertyName = [NSStringstringWithUTF8String:char_f];
id propertyValue = [modelvalueForKey:(NSString *)propertyName];
if (propertyValue)
[props setObject:propertyValueforKey:propertyName];
}
free(properties);
return props;
}
////实现对象的自动赋值
//- (BOOL)reflectDataFromOtherObject:(NSObject*)dataSource
//
//{
// BOOL ret = NO;
// //propertyKeys 其实就是上面的方法的变形,上面方法回传一个可变字典,这里是得到一个可变数组的一个处理
// for (NSString *key in [self propertyKeys])
// {
// if ([dataSource isKindOfClass:[NSDictionary class]])
// {
// ret = ([dataSource valueForKey:key]==nil)?NO:YES;
// }
// else
// {
// ret = [dataSource respondsToSelector:NSSelectorFromString(key)];
// }
// if (ret)
// {
// id propertyValue = [dataSource valueForKey:key];
// //该值不为NSNULL,并且也不为nil
// if (![propertyValue isKindOfClass:[NSNull class]] && propertyValue!=nil)
// {
// [self setValue:propertyValue forKey:key];
// }
// }
// }
// return ret;
//}
@end