一 插件簡介:
其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> @interface BaseBean : NSObject @end //這個NSObject的擴展類 可以查看詳細的建表sql語句 @interface NSObject(PrintSQL) +(NSString*)getCreateTableSQL; @end
*這邊可以放一些其它實體都公有的屬性,及lkdbhelper數據庫的地址;其中PrintSQL是對NSObject的擴展,可以查看創建表的sql語句;
BaseBean.m內容:
// BaseBean.m // LKDBHelperTest // // Created by mac on 16/2/17. // Copyright © 2016年 mac. All rights reserved. // #import "BaseBean.h" @implementation BaseBean /** * 創建數據庫 */ +(LKDBHelper *)getUsingLKDBHelper { static LKDBHelper* db; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSString *sqlitePath = [BaseBean downloadPath]; NSString* dbpath = [sqlitePath stringByAppendingPathComponent:[NSString stringWithFormat:@"lkdbhelperTest.db"]]; db = [[LKDBHelper alloc]initWithDBPath:dbpath]; }); return db; } /** * 數據庫存放路徑 */ + (NSString *)downloadPath{ NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *downloadPath = [documentPath stringByAppendingPathComponent:@"LKHTest"]; NSLog(@"%@",downloadPath); return downloadPath; } @end @implementation NSObject(PrintSQL) /** * 創建數據表 */ +(NSString *)getCreateTableSQL { LKModelInfos* infos = [self getModelInfos]; NSString* primaryKey = [self getPrimaryKey]; NSMutableString* table_pars = [NSMutableString string]; for (int i=0; i<infos.count; i++) { if(i > 0) [table_pars appendString:@","]; LKDBProperty* property = [infos objectWithIndex:i]; [self columnAttributeWithProperty:property]; [table_pars appendFormat:@"%@ %@",property.sqlColumnName,property.sqlColumnType]; if([property.sqlColumnType isEqualToString:LKSQL_Type_Text]) { if(property.length>0) { [table_pars appendFormat:@"(%ld)",(long)property.length]; } } if(property.isNotNull) { [table_pars appendFormat:@" %@",LKSQL_Attribute_NotNull]; } if(property.isUnique) { [table_pars appendFormat:@" %@",LKSQL_Attribute_Unique]; } if(property.checkValue) { [table_pars appendFormat:@" %@(%@)",LKSQL_Attribute_Check,property.checkValue]; } if(property.defaultValue) { [table_pars appendFormat:@" %@ %@",LKSQL_Attribute_Default,property.defaultValue]; } if(primaryKey && [property.sqlColumnName isEqualToString:primaryKey]) { [table_pars appendFormat:@" %@",LKSQL_Attribute_PrimaryKey]; } } NSString* createTableSQL = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@)",[self getTableName],table_pars]; return createTableSQL; } @end
2:子實體CarBean的內容,其是另外一個實體UserBean的一個外鍵
CarBean.h內容:
// // CarBean.h // LKDBHelperTest // // Created by mac on 16/2/17. // Copyright © 2016年 mac. All rights reserved. // #import "BaseBean.h" @interface CarBean : BaseBean @property(assign,nonatomic)int carID; @property(strong,nonatomic)NSString *carNum; @property(strong,nonatomic)NSString *address; @property(assign,nonatomic)float carWidth; @end
CarBean.m內容:
// // CarBean.m // LKDBHelperTest // // Created by mac on 16/2/17. // Copyright © 2016年 mac. All rights reserved. // #import "CarBean.h" @implementation CarBean +(void)initialize { //單個要不顯示時 [self removePropertyWithColumnName:@"address"]; //多列要不顯示時 //[self removePropertyWithColumnNameArray:]; //修改列對應到表時 重命名新列名 [self setTableColumnName:@"MyCarWidth" bindingPropertyName:@"carWidth"]; } /** * @brief 是否將父實體類的屬性也映射到sqlite庫表 * @return BOOL */ +(BOOL) isContainParent{ return YES; } /** * @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 // // Created by mac on 16/2/17. // Copyright © 2016年 mac. All rights reserved. // #import "BaseBean.h" #import "CarBean.h" @interface UserBean : BaseBean @property(assign,nonatomic)int ID; @property(strong,nonatomic)NSString *userName; @property(strong,nonatomic)NSString *password; @property(assign,nonatomic)int age; @property(strong,nonatomic)CarBean *myCar; @end
UserBean.m內容:
// // UserBean.m // LKDBHelperTest // // Created by mac on 16/2/17. // Copyright © 2016年 mac. All rights reserved. // #import "UserBean.h" @implementation UserBean +(void)initialize { [self removePropertyWithColumnName:@"error"]; } /** * @brief 是否將父實體類的屬性也映射到sqlite庫表 * @return BOOL */ +(BOOL) isContainParent{ return YES; } /** * @brief 設定表名 * @return 返回表名 */ +(NSString *)getTableName { return @"userBean"; } /** * @brief 設定表的單個主鍵 * @return 返回主鍵表 */ +(NSString *)getPrimaryKey { return @"ID"; } @end
在ViewController類中測試:
// // ViewController.m // LKDBHelperTest // // Created by mac on 16/2/17. // Copyright © 2016年 mac. All rights reserved. // #import "ViewController.h" #import <LKDBHelper.h> #import "BaseBean.h" #import "UserBean.h" @interface ViewController () @property (strong,nonatomic)LKDBHelper* globalHelper; @property (strong,nonatomic)UserBean *user; @property (strong,nonatomic)CarBean *car; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self test]; } /** * 開始進行針對數據庫進行操作 功能包括刪除所有表,清理指定表的數據,創建表插入數據,其中插入數據會自動判斷表是否存在,若不存在則先創建表再插入,特別說明就是當一個列被定義為int且是主鍵時,它要是沒有被賦值就會自動增長 */ -(void)test{ self.globalHelper = [BaseBean getUsingLKDBHelper]; //刪除所有的表 [self.globalHelper dropAllTable]; //清理所有數據 [LKDBHelper clearTableData:[UserBean class]]; self.user=[[UserBean alloc] init]; //self.user.ID=1000; //特別說明 如果是主鍵 沒給它賦值它就會自動增長 self.user.userName=@"WUJY"; self.user.password=@"123456"; self.user.age=10; self.car=[[CarBean alloc]init]; self.car.carNum=@"D88888"; self.car.address=@"廈門軟件園"; self.car.carWidth=12.5; self.user.myCar=self.car; //插入數據 如果表不存在 它會自動創建再插入 實體實例化LKDBHelper 若是繼承記得引用 否則會沒有效果 [self.user saveToDB]; //另外一種插入 self.user.age=29; [self.globalHelper insertToDB:self.user]; } /** * 關於事務的操作 */ -(void)test2{ //事物 transaction 這邊故意讓它插入失敗 [self.globalHelper executeForTransaction:^BOOL(LKDBHelper *helper) { self.user.ID = 10; self.user.userName=@"wujy10"; BOOL success = [helper insertToDB:self.user]; self.user.ID = 9; self.user.userName=@"wujy09"; success = [helper insertToDB:self.user]; //重復主鍵 self.user.ID = 10; BOOL insertSucceed = [helper insertWhenNotExists:self.user]; //insert fail if(insertSucceed == NO) { ///rollback return NO; } else { ///commit return YES; } }]; } /** * 關於異步操作,對於其它操作也同樣支持異步操作,采用callback方式進行回調 */ -(void)test3{ self.user.userName=@"異步"; [self.globalHelper insertToDB:self.user callback:^(BOOL result) { NSLog(@"異步插入是否成功:%@",result>0?@"是":@"否"); }]; //異步查詢 [self.globalHelper search:[UserBean class] where:nil orderBy:nil offset:0 count:100 callback:^(NSMutableArray *array) { for (id obj in array) { NSLog(@"異步:%@",[obj printAllPropertys]); } }]; } /** * 關於查詢功能的幾種操作,特別注意條件的寫法,其它在代碼中有相應的注解 */ -(void)test4{ NSMutableArray* searchResultArray=nil; //同步搜索 執行sql語句 把結果再變成對象 searchResultArray=[self.globalHelper searchWithSQL:@"select * from @t" toClass:[UserBean class]]; for (id obj in searchResultArray) { NSLog(@"sql語句:%@",[obj printAllPropertys]); } //使用對象對進查詢操作 offset是跳過多少行 count是查詢多少條 searchResultArray=[UserBean searchWithWhere:nil orderBy:nil offset:0 count:100]; for (id obj in searchResultArray) { NSLog(@"實體:%@",[obj printAllPropertys]); } //查詢一列時的操作 count為0時則查所有列 NSArray* nameArray = [UserBean searchColumn:@"userName" where:nil orderBy:nil offset:0 count:0]; NSLog(@"%@",[nameArray componentsJoinedByString:@","]); //查詢多列時的操作 NSArray* twoColumn=[UserBean searchColumn:@"ID,userName" where:nil orderBy:nil offset:0 count:0]; for (UserBean *obj in twoColumn) { NSLog(@"%d-%@",obj.ID,obj.userName); } //組合查詢四種 and or like in searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"userName like '%%JY%%'"] orderBy:nil offset:0 count:0]; NSLog(@"LIKE :%lu",searchResultArray.count); searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"age=29 and userName='WUJY'"] orderBy:nil offset:0 count:0]; NSLog(@"AND :%lu",searchResultArray.count); searchResultArray=[self.globalHelper search:[UserBean class] where:@{@"age":@29,@"userName":@"WUJY"} orderBy:nil offset:0 count:0]; NSLog(@"AND %lu",searchResultArray.count); searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"age=29 or userName='WUJY'"] orderBy:nil offset:0 count:0]; NSLog(@"OR %lu",searchResultArray.count); searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"age in (10,29)"] orderBy:nil offset:0 count:0]; NSLog(@"in %lu",searchResultArray.count); searchResultArray=[self.globalHelper search:[UserBean class] where:@{@"age":@[@10,@29]} orderBy:nil offset:0 count:0]; NSLog(@"in %lu",searchResultArray.count); //查詢符合條件的條數 NSInteger rowCount=[UserBean rowCountWithWhere:@"age=29"]; NSLog(@"rowCount %ld",rowCount); /* *注意: 單條件: @"rowid = 1" 或者 @{@"rowid":@1} 多條件: @“rowid = 1 and sex = 0" 或者 @{@"rowid":@1,@"sex":@0} 如果是or類型的條件,則只能用字符串的形式:@"rowid = 1 or sex = 0" in條件: @"rowid in (1,2,3)" 或者 @{@"rowid":@[@1,@2,@3]} 多條件帶in:@"rowid in (1,2,3) and sex=0 " 或者 @{@"rowid":@[@1,@2,@3],@"sex":@0} 時間也只能用字符串: @"date >= '2013-04-01 00:00:00'" like也只能用字符串: @"userName like '%%JY%%'" */ } /** * 更新操作 */ -(void)test5{ NSMutableArray* searchResultArray=nil; //帶條件更新 self.user.userName=@"踏浪帥"; BOOL isUpDate=[self.globalHelper updateToDB:self.user where:@{@"ID":@10}]; NSLog(@"是否更新成功:%@",isUpDate>0?@"是":@"否"); //根據條件獲得后進行更新 searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"userName='%@'",@"WUJY"] orderBy:nil offset:0 count:100]; self.user=[searchResultArray firstObject]; self.user.password=@"aa123456"; BOOL moreUpdate=[self.globalHelper updateToDB:self.user where:nil]; NSLog(@"根據條件獲得后進行更新:%@",moreUpdate>0?@"是":@"否"); //更新 訪問表名 更新內容跟條件進行更新 BOOL updateTab=[self.globalHelper updateToDBWithTableName:@"userBean" set:@"password='aa123456'" where:@"age=10"]; NSLog(@"訪問表名更新內容跟條件進行更新:%@",updateTab>0?@"是":@"否"); //根據 實類進行更新 BOOL updateClass=[self.globalHelper updateToDB:[UserBean class] set:@"password='cnblogs'" where:@"userName='WUJY'"]; NSLog(@"根據實類進行更新:%@",updateClass>0?@"是":@"否"); } /** * 刪除操作 */ -(void)test6{ //刪除功能 self.user=[self.globalHelper searchSingle:[UserBean class] where:@{@"age":@10} orderBy:nil]; BOOL ishas=[self.globalHelper isExistsModel:self.user]; if (ishas) { [self.globalHelper deleteToDB:self.user]; } //刪除多條 BOOL isDeleteMore=[self.globalHelper deleteWithClass:[UserBean class] where:@"age=29"]; if (isDeleteMore) { NSLog(@"符合條件的都被刪除"); } } @end