LKDBHelper以实体类对象进行数据库的操作,例如新建一个新闻实体类, 很早的时候用过,是基于FMDB基础上封装的,现在记录下使用过程,年纪大了容易健忘 哈哈
#import "BaseDBModel.h"
@implementation BaseDBModel
//在类 初始化的时候
+ (void)initialize {
//如果getTableMapping 返回 nil, 会取全部属性, 如果有不想要的属性,可以使用
[self removePropertyWithColumnName:@"age"];
[self removePropertyWithColumnNameArray:@[@"age", @"name"]];
//修改列名
[self setTableColumnName:@"MyAge" bindingPropertyName:@"age"];
//手动设置关联外键变量名
// [self setUserCalculateForCN:@""];
}
//是否将父实体类的属性也映射到sqlite库表
+ (BOOL)isContainParent {
return YES;
}
+(LKDBHelper *)getUsingLKDBHelper{
static LKDBHelper *helper;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *path = [NSHomeDirectory() stringByAppendingString:@"DB/sqlite.db"];
helper = [[LKDBHelper alloc] initWithDBPath:path];
});
return helper;
}
+(NSString *)getTableName{
return NSStringFromClass([self class]);
}
+(NSString *)getPrimaryKey{
return @"";
}
//手动or自动 绑定sql列
+ (NSDictionary *)getTableMapping {
//返回nil 就是自动绑定所有列名
return nil;
}
+(BOOL)dbWillInsert:(NSObject *)entity{
NSLog(@"will insert");
return YES;
}
//设置列属性====
+(void)columnAttributeWithProperty:(LKDBProperty *)property{
}
@end
#import "ViewController.h"
#import "BaseDBModel.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
LKDBHelper *globalHelper = [BaseDBModel getUsingLKDBHelper];
[globalHelper dropAllTable];
//清空表数据 clear table data
[LKDBHelper clearTableData:[BaseDBModel class]];
BaseDBModel *model = [BaseDBModel new];
model.name = @"老技术";
for (int i = 0; i < 5; i++) {
model.age = i;
[model saveToDB];
}
//查询的操作====
NSMutableArray *searchResultArray = nil;
// sql 1 查找表所有记录
searchResultArray = [BaseDBModel searchWithSQL:@"select *from BaseDBModel"];
searchResultArray = [BaseDBModel searchWithWhere:@"select *from BaseDBModel where age > 0 "];
// 无条件查询 某个列的值
searchResultArray = [BaseDBModel searchColumn:@"age" where:nil orderBy:nil offset:0 count:0];
// 根据一个自增长的列,倒叙查询 最新10条数据 (自增长的列可以是 自定义属性ID,也可以是自带的 rowid)
searchResultArray = [BaseDBModel searchWithWhere:nil orderBy:@"ID desc" offset:0 count:0];
// 根据 and 条件 查询所有数据
searchResultArray = [BaseDBModel searchWithWhere:@"ID = 10 and name = 'laoli'" orderBy:nil offset:0 count:0];
// 根据 in 条件,查询所有数据
searchResultArray = [BaseDBModel searchWithWhere:@"ID in (10,20)" orderBy:nil offset:0 count:0];
BOOL result1 = [BaseDBModel updateToDBWithSet:@"name = '哈哈'" where:@"ID = 10"];
// 根据条件,删除多条数据
BOOL result2 = [BaseDBModel deleteWithWhere:@"name = '哈哈' and ID = 10"];
}
以上就是LKDBHelper的简单使用方法====