标签:
在IOS中 存储数据的sqlite框架有FMDB,其主要的实现还是SQL 语句。而LKDBHelper是构建在该框架上的一个 ORM框架实现对象数据映射。其框架库在github上能找到。以下代码将通过LKDBHelper实现增删查改。
1 实现数据对应的Bean对象,以下提供.h文件。
#import <Foundation/Foundation.h> @interface WBUser : NSObject @property (nonatomic,copy) NSString *userName; @property (nonatomic,assign) int age; @end
WBUserDao.h
#import <Foundation/Foundation.h> #import "WBUser.h" @interface WBUserDao : NSObject +(instancetype)daoWithEntityClass:(Class)aclass; -(void)saveUser:(WBUser *)user; -(WBUser *)loadUserWithWherecase:(NSString *)where; -(BOOL)updateUserWithWherecase:(NSString *)where; -(void)deleteWithWherecase:(NSString *)where; @end
#import "WBUserDao.h" #import "LKDBHelper.h" @interface WBUserDao () @property (nonatomic,strong) Class entityClass; @property (nonatomic,strong) LKDBHelper *gobalHelper; @end @implementation WBUserDao +(instancetype)daoWithEntityClass:(Class)aclass { WBUserDao *dao=[[[self class] alloc] initWithEntityClass:aclass]; return dao; } -(instancetype)initWithEntityClass:(Class)aclass { if (self=[super init]) { _entityClass=aclass; _gobalHelper=[LKDBHelper getUsingLKDBHelper]; [_gobalHelper createTableWithModelClass:[_entityClass class]]; } return self; } -(void)saveUser:(WBUser *)user { NSLog(@"%d",[_gobalHelper insertToDB:user]); } -(WBUser *)loadUserWithWherecase:(NSString *)where { return [_gobalHelper searchSingle:[WBUser class] where:where orderBy:nil]; } -(BOOL)updateUserWithWherecase:(NSString *)where { return [_gobalHelper updateToDB:[WBUser class] set:@"age = 15 " where:where]; } -(void)deleteWithWherecase:(NSString *)where { [_gobalHelper deleteWithClass:[WBUser class] where:where callback:^(BOOL result) { NSLog(@"delete result :%d",result); }]; } @end
- (void)viewDidLoad { [super viewDidLoad]; WBUser *user=[[WBUser alloc] init]; user.userName=@"awdawda"; user.age=18; WBUserDao *dao=[WBUserDao daoWithEntityClass:[user class]]; [dao saveUser:user]; WBUser *userData=[dao loadUserWithWherecase:@"userName='awdawda'"]; BOOL updateFlag=[dao updateUserWithWherecase:@"userName='awdawda'"]; WBUser *userData2=[dao loadUserWithWherecase:@"userName='awdawda'"]; NSLog(@"%d %d",updateFlag,userData2.age); [dao deleteWithWherecase:@"userName='awdawda'"]; }
标签:
原文地址:http://blog.csdn.net/qq285016127/article/details/46351771