您的位置:首页 > 数据库

iOS:LKDBHelper实体对象映射数据库-第三方框架(在FMDB的基础上进行二次封装)

2016-02-17 14:03 561 查看
一插件简介:

其github地址:https://github.com/li6185377/LKDBHelper-SQLite-ORM

全面支持NSArray,NSDictionary,ModelClass,NSNumber,NSString,NSDate,NSData,UIColor,UIImage,CGRect,CGPoint,CGSize,NSRange,int,char,float,double,long..等属性的自动化操作(插入和查询)

二实例内容:

采用pods进行加载LKDBHelper插件,若有下载源代码调试时记得更新一下(平常项目中记得对libsqlite3.dylib进行引用);



本实例创建一个父实体BaseBean,后面其它实体都进行继承

1:父实体的代码内容

BaseBean.h内容:

#import<Foundation/Foundation.h>
#import<LKDBHelper/LKDBHelper.h>

@interfaceBaseBean:NSObject

@end

//这个NSObject的扩展类可以查看详细的建表sql语句
@interfaceNSObject(PrintSQL)

+(NSString*)getCreateTableSQL;

@end


*这边可以放一些其它实体都公有的属性,及lkdbhelper数据库的地址;其中PrintSQL是对NSObject的扩展,可以查看创建表的sql语句;

BaseBean.m内容:

//BaseBean.m
//LKDBHelperTest
//
//Createdbymacon16/2/17.
//Copyright©2016年mac.Allrightsreserved.
//

#import"BaseBean.h"

@implementationBaseBean

/**
*创建数据库
*/
+(LKDBHelper*)getUsingLKDBHelper
{
staticLKDBHelper*db;
staticdispatch_once_tonceToken;
dispatch_once(&onceToken,^{
NSString*sqlitePath=[BaseBeandownloadPath];
NSString*dbpath=[sqlitePathstringByAppendingPathComponent:[NSStringstringWithFormat:@"lkdbhelperTest.db"]];
db=[[LKDBHelperalloc]initWithDBPath:dbpath];
});
returndb;
}

/**
*数据库存放路径
*/
+(NSString*)downloadPath{
NSString*documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)firstObject];
NSString*downloadPath=[documentPathstringByAppendingPathComponent:@"LKHTest"];
NSLog(@"%@",downloadPath);
returndownloadPath;
}
@end

@implementationNSObject(PrintSQL)

/**
*创建数据表
*/
+(NSString*)getCreateTableSQL
{
LKModelInfos*infos=[selfgetModelInfos];
NSString*primaryKey=[selfgetPrimaryKey];
NSMutableString*table_pars=[NSMutableStringstring];
for(inti=0;i<infos.count;i++){

if(i>0)
[table_parsappendString:@","];

LKDBProperty*property=[infosobjectWithIndex:i];
[selfcolumnAttributeWithProperty:property];

[table_parsappendFormat:@"%@%@",property.sqlColumnName,property.sqlColumnType];

if([property.sqlColumnTypeisEqualToString:LKSQL_Type_Text])
{
if(property.length>0)
{
[table_parsappendFormat:@"(%ld)",(long)property.length];
}
}
if(property.isNotNull)
{
[table_parsappendFormat:@"%@",LKSQL_Attribute_NotNull];
}
if(property.isUnique)
{
[table_parsappendFormat:@"%@",LKSQL_Attribute_Unique];
}
if(property.checkValue)
{
[table_parsappendFormat:@"%@(%@)",LKSQL_Attribute_Check,property.checkValue];
}
if(property.defaultValue)
{
[table_parsappendFormat:@"%@%@",LKSQL_Attribute_Default,property.defaultValue];
}
if(primaryKey&&[property.sqlColumnNameisEqualToString:primaryKey])
{
[table_parsappendFormat:@"%@",LKSQL_Attribute_PrimaryKey];
}
}
NSString*createTableSQL=[NSStringstringWithFormat:@"CREATETABLEIFNOTEXISTS%@(%@)",[selfgetTableName],table_pars];
returncreateTableSQL;
}

@end


2:子实体CarBean的内容,其是另外一个实体UserBean的一个外键

CarBean.h内容:


//
//CarBean.h
//LKDBHelperTest
//
//Createdbymacon16/2/17.
//Copyright©2016年mac.Allrightsreserved.
//

#import"BaseBean.h"

@interfaceCarBean:BaseBean

@property(assign,nonatomic)intcarID;
@property(strong,nonatomic)NSString*carNum;
@property(strong,nonatomic)NSString*address;
@property(assign,nonatomic)floatcarWidth;

@end


CarBean.m内容:


//
//CarBean.m
//LKDBHelperTest
//
//Createdbymacon16/2/17.
//Copyright©2016年mac.Allrightsreserved.
//

#import"CarBean.h"

@implementationCarBean

+(void)initialize
{
//单个要不显示时
[selfremovePropertyWithColumnName:@"address"];

//多列要不显示时
//[selfremovePropertyWithColumnNameArray:];

//修改列对应到表时重命名新列名
[selfsetTableColumnName:@"MyCarWidth"bindingPropertyName:@"carWidth"];
}

/**
*@brief是否将父实体类的属性也映射到sqlite库表
*@returnBOOL
*/
+(BOOL)isContainParent{
returnYES;
}
/**
*@brief设定表名
*@return返回表名
*/
+(NSString*)getTableName
{
return@"carbean";
}
/**
*@brief设定表的单个主键
*@return返回主键表
*/
+(NSString*)getPrimaryKey
{
return@"carID";
}

/////复合主键这个优先级最高
//+(NSArray*)getPrimaryKeyUnionArray
//{
//return@[@"carID",@"carNum"];
//}

@end


*主要注意关于可以把一些属性过滤掉,就不会创建到表中,也可以对列名进行重定义,其它几个代码有详细说明

3:子实体UserBean,同样继承BaseBean

UserBean.h内容:


//
//UserBean.h
//LKDBHelperTest
//
//Createdbymacon16/2/17.
//Copyright©2016年mac.Allrightsreserved.
//

#import"BaseBean.h"
#import"CarBean.h"

@interfaceUserBean:BaseBean

@property(assign,nonatomic)intID;
@property(strong,nonatomic)NSString*userName;
@property(strong,nonatomic)NSString*password;
@property(assign,nonatomic)intage;

@property(strong,nonatomic)CarBean*myCar;

@end


UserBean.m内容:


//
//UserBean.m
//LKDBHelperTest
//
//Createdbymacon16/2/17.
//Copyright©2016年mac.Allrightsreserved.
//

#import"UserBean.h"

@implementationUserBean

+(void)initialize
{
[selfremovePropertyWithColumnName:@"error"];
}

/**
*@brief是否将父实体类的属性也映射到sqlite库表
*@returnBOOL
*/
+(BOOL)isContainParent{
returnYES;
}
/**
*@brief设定表名
*@return返回表名
*/
+(NSString*)getTableName
{
return@"userBean";
}
/**
*@brief设定表的单个主键
*@return返回主键表
*/
+(NSString*)getPrimaryKey
{
return@"ID";
}

@end


在ViewController类中测试:

//
//ViewController.m
//LKDBHelperTest
//
//Createdbymacon16/2/17.
//Copyright©2016年mac.Allrightsreserved.
//

#import"ViewController.h"
#import<LKDBHelper.h>
#import"BaseBean.h"
#import"UserBean.h"

@interfaceViewController()
@property(strong,nonatomic)LKDBHelper*globalHelper;
@property(strong,nonatomic)UserBean*user;
@property(strong,nonatomic)CarBean*car;
@end

@implementationViewController

-(void)viewDidLoad{
[superviewDidLoad];

[selftest];
}

/**
*开始进行针对数据库进行操作
功能包括删除所有表,清理指定表的数据,创建表插入数据,其中插入数据会自动判断表是否存在,若不存在则先创建表再插入,特别说明就是当一个列被定义为int且是主键时,它要是没有被赋值就会自动增长
*/
-(void)test{

self.globalHelper=[BaseBeangetUsingLKDBHelper];

//删除所有的表
[self.globalHelperdropAllTable];

//清理所有数据
[LKDBHelperclearTableData:[UserBeanclass]];

self.user=[[UserBeanalloc]init];
//self.user.ID=1000;//特别说明如果是主键没给它赋值它就会自动增长
self.user.userName=@"WUJY";
self.user.password=@"123456";
self.user.age=10;

self.car=[[CarBeanalloc]init];
self.car.carNum=@"D88888";
self.car.address=@"厦门软件园";
self.car.carWidth=12.5;

self.user.myCar=self.car;

//插入数据如果表不存在它会自动创建再插入实体实例化LKDBHelper若是继承记得引用否则会没有效果
[self.usersaveToDB];

//另外一种插入
self.user.age=29;
[self.globalHelperinsertToDB:self.user];
}

/**
*关于事务的操作
*/
-(void)test2{

//事物transaction这边故意让它插入失败
[self.globalHelperexecuteForTransaction:^BOOL(LKDBHelper*helper){

self.user.ID=10;
self.user.userName=@"wujy10";
BOOLsuccess=[helperinsertToDB:self.user];

self.user.ID=9;
self.user.userName=@"wujy09";
success=[helperinsertToDB:self.user];

//重复主键
self.user.ID=10;
BOOLinsertSucceed=[helperinsertWhenNotExists:self.user];

//insertfail
if(insertSucceed==NO)
{
///rollback
returnNO;
}
else
{
///commit
returnYES;
}
}];
}

/**
*关于异步操作,对于其它操作也同样支持异步操作,采用callback方式进行回调
*/
-(void)test3{

self.user.userName=@"异步";
[self.globalHelperinsertToDB:self.usercallback:^(BOOLresult){
NSLog(@"异步插入是否成功:%@",result>0?@"是":@"否");
}];

//异步查询
[self.globalHelpersearch:[UserBeanclass]where:nilorderBy:niloffset:0count:100callback:^(NSMutableArray*array){
for(idobjinarray){
NSLog(@"异步:%@",[objprintAllPropertys]);
}
}];
}

/**
*关于查询功能的几种操作,特别注意条件的写法,其它在代码中有相应的注解
*/
-(void)test4{

NSMutableArray*searchResultArray=nil;

//同步搜索执行sql语句把结果再变成对象
searchResultArray=[self.globalHelpersearchWithSQL:@"select*from@t"toClass:[UserBeanclass]];
for(idobjinsearchResultArray){
NSLog(@"sql语句:%@",[objprintAllPropertys]);
}

//使用对象对进查询操作offset是跳过多少行count是查询多少条
searchResultArray=[UserBeansearchWithWhere:nilorderBy:niloffset:0count:100];
for(idobjinsearchResultArray){
NSLog(@"实体:%@",[objprintAllPropertys]);
}

//查询一列时的操作count为0时则查所有列
NSArray*nameArray=[UserBeansearchColumn:@"userName"where:nilorderBy:niloffset:0count:0];
NSLog(@"%@",[nameArraycomponentsJoinedByString:@","]);

//查询多列时的操作
NSArray*twoColumn=[UserBeansearchColumn:@"ID,userName"where:nilorderBy:niloffset:0count:0];
for(UserBean*objintwoColumn){
NSLog(@"%d-%@",obj.ID,obj.userName);
}

//组合查询四种andorlikein
searchResultArray=[UserBeansearchWithWhere:[NSStringstringWithFormat:@"userNamelike'%%JY%%'"]orderBy:niloffset:0count:0];
NSLog(@"LIKE:%lu",searchResultArray.count);

searchResultArray=[UserBeansearchWithWhere:[NSStringstringWithFormat:@"age=29anduserName='WUJY'"]orderBy:niloffset:0count:0];
NSLog(@"AND:%lu",searchResultArray.count);

searchResultArray=[self.globalHelpersearch:[UserBeanclass]where:@{@"age":@29,@"userName":@"WUJY"}orderBy:niloffset:0count:0];
NSLog(@"AND%lu",searchResultArray.count);

searchResultArray=[UserBeansearchWithWhere:[NSStringstringWithFormat:@"age=29oruserName='WUJY'"]orderBy:niloffset:0count:0];
NSLog(@"OR%lu",searchResultArray.count);

searchResultArray=[UserBeansearchWithWhere:[NSStringstringWithFormat:@"agein(10,29)"]orderBy:niloffset:0count:0];
NSLog(@"in%lu",searchResultArray.count);

searchResultArray=[self.globalHelpersearch:[UserBeanclass]where:@{@"age":@[@10,@29]}orderBy:niloffset:0count:0];
NSLog(@"in%lu",searchResultArray.count);

//查询符合条件的条数
NSIntegerrowCount=[UserBeanrowCountWithWhere:@"age=29"];
NSLog(@"rowCount%ld",rowCount);

/*

*注意:

单条件:
@"rowid=1"或者@{@"rowid":@1}

多条件:
@“rowid=1andsex=0"或者@{@"rowid":@1,@"sex":@0}
如果是or类型的条件,则只能用字符串的形式:@"rowid=1orsex=0"

in条件:
@"rowidin(1,2,3)"或者@{@"rowid":@[@1,@2,@3]}
多条件带in:@"rowidin(1,2,3)andsex=0"或者@{@"rowid":@[@1,@2,@3],@"sex":@0}

时间也只能用字符串:
@"date>='2013-04-0100:00:00'"

like也只能用字符串:
@"userNamelike'%%JY%%'"

*/
}

/**
*更新操作
*/
-(void)test5{

NSMutableArray*searchResultArray=nil;

//带条件更新
self.user.userName=@"踏浪帅";
BOOLisUpDate=[self.globalHelperupdateToDB:self.userwhere:@{@"ID":@10}];
NSLog(@"是否更新成功:%@",isUpDate>0?@"是":@"否");

//根据条件获得后进行更新
searchResultArray=[UserBeansearchWithWhere:[NSStringstringWithFormat:@"userName='%@'",@"WUJY"]orderBy:niloffset:0count:100];
self.user=[searchResultArrayfirstObject];
self.user.password=@"aa123456";
BOOLmoreUpdate=[self.globalHelperupdateToDB:self.userwhere:nil];
NSLog(@"根据条件获得后进行更新:%@",moreUpdate>0?@"是":@"否");

//更新访问表名更新内容跟条件进行更新
BOOLupdateTab=[self.globalHelperupdateToDBWithTableName:@"userBean"set:@"password='aa123456'"where:@"age=10"];
NSLog(@"访问表名更新内容跟条件进行更新:%@",updateTab>0?@"是":@"否");

//根据实类进行更新
BOOLupdateClass=[self.globalHelperupdateToDB:[UserBeanclass]set:@"password='cnblogs'"where:@"userName='WUJY'"];
NSLog(@"根据实类进行更新:%@",updateClass>0?@"是":@"否");
}

/**
*删除操作
*/
-(void)test6{

//删除功能
self.user=[self.globalHelpersearchSingle:[UserBeanclass]where:@{@"age":@10}orderBy:nil];
BOOLishas=[self.globalHelperisExistsModel:self.user];
if(ishas){
[self.globalHelperdeleteToDB:self.user];
}

//删除多条
BOOLisDeleteMore=[self.globalHelperdeleteWithClass:[UserBeanclass]where:@"age=29"];
if(isDeleteMore){
NSLog(@"符合条件的都被删除");
}
}
@end






                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: