码迷,mamicode.com
首页 > 移动开发 > 详细

IOS项目练习 之 "爱限免" 项目笔记(二) - 数据库篇

时间:2015-04-11 17:42:17      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

在这个练习项目中我们用到了Sqlite3 数据库,这里使用了第三方开源库FMDB,但是直接操作FMDB太麻烦了,所以又在上面加了一层封装;

为了保证代码的通用性,我写的时候尽量将实体和数据库操作分离,实在没有办法分离的地方就使用预编译命令代替,下面是我的数据库封装的代码

 1 //
 2 //  DatabaseManager.h
 3 //  FreeLimit
 4 //
 5 //  Created by TBXark on 15-4-10.
 6 //  Copyright (c) 2015年 TBXark. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 //实体的类名,当执行Select操作视直接返回实体
12 #define kEntityClassName   @"AppModel"
13 
14 //自动增长主键名
15 #define kAutoIncrementKey  @"id"
16 
17 //约束键名
18 #define kUniqueKey         @"applicationId"
19 #define kUniqueKeySecond   @"recordType"
20 
21 //表的所有列名
22 #define kTableKey          @[@"recordType",23                              @"applicationId",24                              @"name",25                              @"iconUrl",26                              @"type",27                              @"lastPrice",28                              @"currentPrice"];
29 
30 //是否阻止约束对象插入
31 #define kCanNotInsertWhenUniqueDefine
32 
33 @interface DatabaseManager : NSObject
34 
35 @property (nonatomic,strong) NSMutableDictionary *indexDict;
36 
37 
38 + (instancetype)shareManager;
39 
40 - (BOOL)insertIntoTable:(id)model;
41 - (id)selectFromTable:(NSString *)query;
42 - (NSArray *)selectMultFromTable:(NSString *)query;
43 - (BOOL)deleteFromTable:(NSString *)query;
44 - (BOOL)updateFromTable:(NSString *)query entity:(id)model;
45 
46 - (NSDictionary *)createIndexForTable;
47 
48 #ifndef kUniqueKeySecond
49 - (BOOL)checkExistWithUniqueKey:(NSString *)uniqueKey;
50 #else
51 - (BOOL)checkExistWithUniqueKey:(NSString *)uniqueKey secondKey:(NSString *)secondKey;
52 #endif
53 
54 @end
  1 //
  2 //  DatabaseManager.m
  3 //  FreeLimit
  4 //
  5 //  Created by TBXark on 15-4-10.
  6 //  Copyright (c) 2015年 TBXark. All rights reserved.
  7 //
  8 
  9 #import "DatabaseManager.h"
 10 #import "FMDatabase.h"
 11 #import "NSObject+EntityHelper.h"
 12 
 13 static DatabaseManager *_mainDataBaseManager;
 14 
 15 //基本的SQL查询语句
 16 
 17 #define kCreateTable       @"create table if not exists applist  ("  18                             " id integer primary key autoincrement not null, "  19                             " recordType varchar(32), "  20                             " applicationId integer not null, "  21                             " name varchar(128), "  22                             " iconUrl varchar(1024), "  23                             " type varchar(32) ,"  24                             " lastPrice integer, "  25                             " currentPrice integer "  26                             ",UNIQUE(applicationId,recordType)"  27                             ");"
 28 
 29 #define kInsertIntoTable   @"INSERT INTO applist(" 30                             "recordType,"  31                             "applicationId,"  32                             "name,"  33                             "iconUrl,"  34                             "type,"  35                             "lastPrice,"  36                             "currentPrice) "  37                             "VALUES("  38                             ":recordType,"  39                             ":applicationId,"  40                             ":name,:iconUrl,"  41                             ":type,"  42                             ":lastPrice,"  43                             ":currentPrice "  44                             ");"
 45 
 46 #define kUpdateTable       @"UPDATE applist SET "  47                             "recordType = :recordType"  48                             "applicationId = :applicationId,"  49                             "name = :name,"  50                             "iconUrl = :iconUrl,"  51                             "type = :type,"  52                             "lastPrice = :lastPrice,"  53                             "currentPrice = :currentPrice"  54                             "WHERE %@;);"
 55 
 56 #define kSelectAll         @"SELECT * FROM applist WHERE %@;"
 57 
 58 #define kCreateIndex       @"SELECT id,applicationId,recordType FROM applist;"
 59 
 60 #define kDeleteFromTable   @"DELETE FROM applist WHERE %@;"
 61 
 62 #define kDataBaseName      @"DataBase.sqlite"
 63 
 64 
 65 @interface DatabaseManager ()
 66 
 67 @property (strong,nonatomic) FMDatabase *db;
 68 
 69 
 70 @end
 71 
 72 @implementation DatabaseManager
 73 
 74 + (instancetype)shareManager
 75 {
 76     static dispatch_once_t onceToken;
 77     dispatch_once(&onceToken, ^{
 78         if (_mainDataBaseManager == nil) {
 79             _mainDataBaseManager = [[DatabaseManager alloc] init];
 80             [_mainDataBaseManager createTable];
 81             [_mainDataBaseManager createIndexForTable];
 82         }
 83     });
 84     return _mainDataBaseManager;
 85 }
 86 
 87 - (void)createTable
 88 {
 89     NSString *createTableStr = kCreateTable;
 90     NSString *dbPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",kDataBaseName];
 91     _db = [FMDatabase databaseWithPath:dbPath];
 92     if ([_db open]) {
 93         NSLog(@"Open in path : %@",dbPath);
 94         [_db executeUpdate:createTableStr];
 95         [_db close];
 96     }else
 97     {
 98         NSLog(@"Can not open");
 99         [_db close];
100     }
101 }
102 
103 - (BOOL)insertIntoTable:(id)model
104 {
105     NSDictionary *dict = [self createDictFromDict:[model entityToDictionary]];
106 
107 #ifdef kCanNotInsertWhenUniqueDefine
108     if ([[_indexDict allValues] containsObject:dict[kUniqueKey]]) {
109         NSLog(@"Can Not Insert Exist Object When Unique Define is Enable");
110         return NO;
111     }
112 #endif
113     if ([_db open]) {
114         [_db executeUpdate:kInsertIntoTable withParameterDictionary:dict];
115         [_db close];
116         [self createIndexForTable];
117         return YES;
118     }
119     return NO;
120 }
121 
122 - (id)selectFromTable:(NSString *)query
123 {
124     if ([_db open]) {
125         FMResultSet *set = [_db executeQuery:[NSString stringWithFormat:kSelectAll,query]];
126         NSDictionary *dict;
127         if ([set next]) {
128             dict = [set resultDictionary];
129             if (dict) {
130 //                根据结果集创建实体
131                 id  entity = [[NSClassFromString(kEntityClassName) alloc] init];
132                 [entity setValuesForKeysWithDictionary:dict];
133                 [_db close];
134                 return entity;
135             }
136         }
137     }
138     return nil;
139 }
140 
141 - (NSArray *)selectMultFromTable:(NSString *)query
142 {
143     if ([_db open]) {
144         FMResultSet *set = [_db executeQuery:[NSString stringWithFormat:kSelectAll,query]];
145         NSMutableArray *resultArry = [[NSMutableArray alloc] init];
146         NSDictionary *dict;
147         while([set next]) {
148             dict = [set resultDictionary];
149             if (dict) {
150                 id  entity = [[NSClassFromString(kEntityClassName) alloc] init];
151                 [entity setValuesForKeysWithDictionary:dict];
152                 [resultArry addObject:entity];
153             }
154         }
155         [_db close];
156         return resultArry;
157     }
158     return nil;
159 }
160 
161 - (BOOL)deleteFromTable:(NSString *)query
162 {
163     if ([_db open]) {
164         BOOL result = [_db executeUpdate:[NSString stringWithFormat:kDeleteFromTable,query]];
165         [self createIndexForTable];
166         return result;
167     }
168     return NO;
169 }
170 
171 - (BOOL)updateFromTable:(NSString *)query entity:(id)model
172 {
173     if ([_db open]) {
174         NSDictionary *dict = [self createDictFromDict:[model entityToDictionary]];
175         NSString *updateStr = [NSString stringWithFormat:kUpdateTable,query];
176         BOOL result = [_db executeUpdate:updateStr,dict];
177         [self createIndexForTable];
178         return result;
179     }
180     return NO;
181 }
182 
183 - (NSDictionary *)createIndexForTable
184 {
185     if ([_db open]) {
186         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
187         FMResultSet *set = [_db executeQuery:kCreateIndex];
188         while ([set next]) {
189             NSNumber *num = [NSNumber numberWithInteger:[set intForColumn:kAutoIncrementKey]];
190             NSString *uniqueValue = [set stringForColumn:kUniqueKey];
191             
192 #ifndef kUniqueKeySecond
193             NSDictionary *dictTemp = @{kUniqueKey:uniqueValue};
194 #else
195             NSString *secondUniqueValue = [set stringForColumn:kUniqueKeySecond];
196             NSDictionary *dictTemp = @{kUniqueKey:uniqueValue,
197                                        kUniqueKeySecond:secondUniqueValue};
198 #endif
199             
200             [dict setObject:dictTemp forKey:num];
201         }
202         _indexDict = dict;
203         return dict;
204     }
205     return nil;
206 }
207 
208 
209 - (NSDictionary *)createDictFromDict:(NSDictionary *)dict
210 {
211     NSArray *keyArry = kTableKey;
212     if (dict[kUniqueKey] == nil) {
213         return nil;
214     }
215     NSMutableDictionary *dictTemp = [[NSMutableDictionary alloc] init];
216      for (NSString *key in keyArry) {
217         NSString *value = dict[key];
218         if (value) {
219             [dictTemp setObject:value forKey:key];
220         }else
221         {
222             [dictTemp setObject:@"NULL" forKey:key];
223         }
224     }
225     return dictTemp;
226 }
227 
228 
229 
230 
231 #ifndef kUniqueKeySecond
232 - (BOOL)checkExistWithUniqueKey:(NSString *)uniqueKey
233 {
234     for (NSNumber *key in _indexDict) {
235         NSDictionary *dict = _indexDict[key];
236         if ([dict[kUniqueKey] isEqualToString:uniqueKey]) {
237             return YES;
238         }
239 }
240 return NO;
241 #else
242 - (BOOL)checkExistWithUniqueKey:(NSString *)uniqueKey secondKey:(NSString *)secondKey
243 {
244     for (NSNumber *key in _indexDict) {
245         NSDictionary *dict = _indexDict[key];
246         if ([dict[kUniqueKey] isEqualToString:uniqueKey] &&[dict[kUniqueKeySecond] isEqualToString:secondKey]) {
247             return YES;
248         }
249     }
250     return NO;
251 }
252 #endif
253 
254 
255 
256 @end

写在后面的话:

这个项目大部分的功能和界面已经完成,可以到我的gitHub上查看完整版代码 : https://github.com/vfanx/FreeLimit

IOS项目练习 之 "爱限免" 项目笔记(二) - 数据库篇

标签:

原文地址:http://www.cnblogs.com/vfanx/p/4417924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!