├── .gitignore ├── DBDemo ├── Classes │ ├── GXCache.h │ ├── GXCache.m │ ├── GXDatabaseManager.h │ ├── GXDatabaseManager.m │ ├── GXHeader.h │ ├── GXSQLStatementManager.h │ ├── GXSQLStatementManager.m │ ├── NSObject+serializable.h │ └── NSObject+serializable.m ├── DBDemo.xcodeproj │ └── project.pbxproj ├── DBDemo │ ├── AppDelegate.h │ ├── AppDelegate.m │ ├── Base.lproj │ │ ├── LaunchScreen.xib │ │ └── Main.storyboard │ ├── DataModel │ │ ├── GXMessage.h │ │ ├── GXMessage.m │ │ ├── GXMessageDBEntity.h │ │ └── GXMessageDBEntity.m │ ├── Images.xcassets │ │ ├── AppIcon.appiconset │ │ │ └── Contents.json │ │ ├── Contents.json │ │ └── LaunchImage.launchimage │ │ │ ├── Contents.json │ │ │ ├── default_1.png │ │ │ ├── default_2.png │ │ │ ├── default_3.png │ │ │ ├── default_4.png │ │ │ └── default_5.png │ ├── Info.plist │ ├── ViewController.h │ ├── ViewController.m │ ├── fmdb │ │ ├── FMDB.h │ │ ├── FMDatabase.h │ │ ├── FMDatabase.m │ │ ├── FMDatabaseAdditions.h │ │ ├── FMDatabaseAdditions.m │ │ ├── FMDatabasePool.h │ │ ├── FMDatabasePool.m │ │ ├── FMDatabaseQueue.h │ │ ├── FMDatabaseQueue.m │ │ ├── FMResultSet.h │ │ └── FMResultSet.m │ ├── main.m │ ├── play.playground │ │ ├── contents.xcplayground │ │ ├── section-1.swift │ │ └── timeline.xctimeline │ └── resource │ │ ├── db.sqlite │ │ ├── iphone-100.png │ │ ├── iphone-25.png │ │ ├── iphone-25@2x.png │ │ └── iphone-512.png ├── DBDemoTests │ ├── DBDemoTests.m │ └── Info.plist └── GXDatabaseUtils.podspec ├── LICENSE ├── README.md ├── docs └── screen_shot.png └── testDB.xcworkspace ├── contents.xcworkspacedata └── xcshareddata └── IDEWorkspaceChecks.plist /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | .DS_Store 4 | build/ 5 | *.pbxuser 6 | !default.pbxuser 7 | *.mode1v3 8 | !default.mode1v3 9 | *.mode2v3 10 | !default.mode2v3 11 | *.perspectivev3 12 | !default.perspectivev3 13 | xcuserdata 14 | *.xccheckout 15 | *.moved-aside 16 | DerivedData 17 | *.hmap 18 | *.ipa 19 | *.xcuserstate 20 | 21 | # CocoaPods 22 | # 23 | # We recommend against adding the Pods directory to your .gitignore. However 24 | # you should judge for yourself, the pros and cons are mentioned at: 25 | # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control 26 | # 27 | # Pods/ 28 | -------------------------------------------------------------------------------- /DBDemo/Classes/GXCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // GXCache.h 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | // for memberListCacheDictionary 12 | #define kKeyClassName @"className" 13 | #define kKeyMemberList @"memberList" 14 | 15 | 16 | 17 | @interface GXCache : NSObject { 18 | 19 | NSMutableDictionary *_memberListCacheDictionary; 20 | } 21 | 22 | + (instancetype) defaultCache; 23 | 24 | - (NSArray *)memberListByName:(NSString *)className; 25 | - (NSArray *)memberListByClass:(Class)cls; 26 | 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /DBDemo/Classes/GXCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // GXCache.m 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import "GXCache.h" 10 | #import 11 | #import "NSObject+serializable.h" 12 | #import "GXSQLStatementManager.h" 13 | 14 | @implementation GXCache 15 | 16 | + (instancetype) defaultCache { 17 | 18 | static GXCache *cache = nil; 19 | 20 | static dispatch_once_t onceToken; 21 | dispatch_once(&onceToken, ^{ 22 | 23 | if (!cache) { 24 | cache = [[self alloc] init]; 25 | } 26 | }); 27 | 28 | return cache; 29 | } 30 | 31 | - (id) init { 32 | 33 | self = [super init]; 34 | 35 | if (self) { 36 | _memberListCacheDictionary = [[NSMutableDictionary alloc] init]; 37 | } 38 | 39 | return self; 40 | } 41 | 42 | 43 | - (NSArray *)memberListByName:(NSString *)className { 44 | 45 | NSArray *arr = _memberListCacheDictionary[className]; 46 | 47 | if (!arr) { 48 | arr = [GXCache generateMemberListByClass:NSClassFromString(className)]; 49 | if (arr) { 50 | [_memberListCacheDictionary setObject:arr forKey:className]; 51 | } 52 | } 53 | 54 | return arr; 55 | } 56 | 57 | - (NSArray *)memberListByClass:(Class)cls { 58 | 59 | NSString *clsName = NSStringFromClass(cls); 60 | return [self memberListByName:clsName]; 61 | } 62 | 63 | + (NSArray *)generateMemberListByClass:(Class) cls { 64 | 65 | NSMutableArray *members = [NSMutableArray array]; 66 | 67 | // 68 | // 枚举cls的成员及类型 69 | // 70 | NSString *clsName = NSStringFromClass(cls); 71 | 72 | while (![clsName isEqualToString:NSStringFromClass([NSObject class])]) { 73 | 74 | unsigned count = 0; 75 | Ivar *vars = class_copyIvarList(cls, &count); 76 | 77 | NSLog(@"------------------Class %@ start-----------------------", clsName); 78 | 79 | for (int i = 0; i < count; i++) { 80 | 81 | NSString *mName = [NSObject memberNameWithIvars:vars atIndex:i]; 82 | NSString *mType = [NSObject memberTypeWithIvars:vars atIndex:i]; 83 | NSString *sType = [GXSQLStatementManager sqlTypeWithMemberType:mType]; 84 | 85 | if (nil == sType) { 86 | NSLog(@"ERROR:Skipped not supported(Member Name:%@, Member Type:%@)", mName, mType); 87 | continue; 88 | } 89 | 90 | NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; 91 | [dictionary setObject:mName forKey:kKeyMemberName]; 92 | [dictionary setObject:mType forKey:kKeyMemberType]; 93 | [dictionary setObject:sType forKey:kKeySqliteType]; 94 | 95 | [members addObject:dictionary]; 96 | 97 | } 98 | free(vars); 99 | NSLog(@"------------------Class %@ end-----------------------", clsName); 100 | 101 | cls = [cls superclass]; 102 | clsName = NSStringFromClass(cls); 103 | } 104 | 105 | return members; 106 | } 107 | 108 | @end 109 | -------------------------------------------------------------------------------- /DBDemo/Classes/GXDatabaseManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // GXDatabaseManager.h 3 | // GXDatabaseManager 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "GXHeader.h" 11 | 12 | @interface GXDatabaseManager : NSObject 13 | 14 | + (BOOL) databaseWithPath:(NSString *)path; 15 | + (void) closeDatabase; 16 | 17 | + (BOOL) createTable:(NSString *)tableName withClass:(Class)cls withPrimaryKey:(NSString *)primaryKey; 18 | 19 | + (BOOL) replaceInto:(NSString *)tableName withObject:(id)object; 20 | 21 | + (BOOL)updateTable:(NSString *)tableName set:(NSArray *)params where:(NSString *)whereString withParams:(NSArray *)values; 22 | 23 | + (NSArray *)selectObjects:(Class)cls fromTable:(NSString *)tableName where:(NSString *)whereString withParams:(NSArray *)params orderBy:(NSString *)obString withSortType:(NSString *)type withRange:(NSRange)range; 24 | 25 | + (NSInteger)selectCountFrom:(NSString *)tableName where:(NSString *)whereString withParams:(NSArray *)params; 26 | 27 | + (BOOL)deleteTable:(NSString *)tableName where:(NSString *)whereString withParams:(NSArray *)params; 28 | @end 29 | -------------------------------------------------------------------------------- /DBDemo/Classes/GXDatabaseManager.m: -------------------------------------------------------------------------------- 1 | // 2 | // GXDatabaseManager.m 3 | // GXDatabaseManager 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import "GXDatabaseManager.h" 10 | #import "FMDatabase.h" 11 | #import "GXSQLStatementManager.h" 12 | #import "NSObject+serializable.h" 13 | #import "GXCache.h" 14 | 15 | 16 | static FMDatabase *database = nil; 17 | 18 | @implementation GXDatabaseManager 19 | 20 | + (BOOL) databaseWithPath:(NSString *)path { 21 | // TODO: 每次都重新初始化数据库,根据情况修改 22 | // if (!database) { 23 | database = [FMDatabase databaseWithPath:path]; 24 | // } 25 | 26 | if (![database open]) { 27 | NSLog(@"open database failure."); 28 | return NO; 29 | } 30 | 31 | return YES; 32 | } 33 | 34 | 35 | + (void) closeDatabase { 36 | 37 | if (database) { 38 | [database close]; 39 | database = nil; 40 | } 41 | } 42 | 43 | // 创建 44 | + (BOOL) createTable:(NSString *)tableName withClass:(Class)cls withPrimaryKey:(NSString *)primaryKey { 45 | 46 | NSString *createSQL = [GXSQLStatementManager create:tableName 47 | withClass:cls 48 | withPrimaryKey:primaryKey]; 49 | 50 | BOOL res = [database executeUpdate:createSQL]; 51 | 52 | if (!res) { 53 | #if ENABLED_SQL_ERROR_LOG 54 | NSLog(@"DB CREATE TABLE %@(%@)", tableName, [database lastErrorMessage]); 55 | #endif 56 | } 57 | 58 | return res; 59 | } 60 | 61 | // 62 | // insert into users values(:id, :name, :age) 63 | // 64 | + (BOOL) replaceInto:(NSString *)tableName withObject:(id)object { 65 | 66 | NSDictionary *dict = [object dictionary]; 67 | 68 | NSArray *memberList = [[GXCache defaultCache] memberListByClass:[object class]]; 69 | 70 | if (!memberList || 0 == memberList.count) { 71 | return NO; 72 | } 73 | 74 | NSMutableString *paramList = [NSMutableString string]; 75 | [memberList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 76 | NSDictionary *dict = memberList[idx]; 77 | NSString *mName = dict[kKeyMemberName]; 78 | 79 | [paramList appendString:[NSString stringWithFormat:@":%@", mName]]; 80 | 81 | if (idx != memberList.count - 1) { 82 | [paramList appendString:@","]; 83 | } 84 | }]; 85 | 86 | 87 | NSString *sql = [GXSQLStatementManager replaceInto:tableName withParameterList:paramList]; 88 | BOOL res = [database executeUpdate:sql withParameterDictionary:dict]; 89 | 90 | if (!res) { 91 | #if ENABLED_SQL_ERROR_LOG 92 | NSLog(@"DB REPLACE INTO %@(%@)", tableName, [database lastErrorMessage]); 93 | #endif 94 | } 95 | 96 | return res; 97 | } 98 | 99 | 100 | + (BOOL)updateTable:(NSString *)tableName set:(NSArray *)params where:(NSString *)whereString withParams:(NSArray *)values { 101 | 102 | NSString *updateSQL = [GXSQLStatementManager update:tableName set:params where:whereString]; 103 | if (!updateSQL) return NO; 104 | 105 | BOOL res = [database executeUpdate:updateSQL withArgumentsInArray:values]; 106 | if(!res) { 107 | #if ENABLED_SQL_ERROR_LOG 108 | NSLog(@"DB UPDATE TABLE %@(%@)", tableName, [database lastErrorMessage]); 109 | #endif 110 | } 111 | 112 | return res; 113 | } 114 | 115 | 116 | // 117 | // SELECT * FROM film WHERE starring LIKE 'Jodie%' AND year >= 1985 ORDER BY year DESC LIMIT 10; 118 | // 119 | // SELECT COUNT(*) FROM film; 120 | // SELECT COUNT(*) FROM film WHERE year >= 1985; 121 | // 122 | // SELECT * FROM person WHERE name LIKE ? and AND age=?", @"gerry", @(20) 123 | // 124 | // SELECT * FROM film WHERE starring = 'Jodie Foster' AND year >= 1985 ORDER BY year DESC LIMIT 10; 125 | // ---- -------- ~ ============= ~~~ ---- ~~ ==== ---- ---- == 126 | // | | | | | | | | | 127 | // tableName | | operator | logic operator | obString | range 128 | // |columnName columnValue | sType 129 | // ------------------------------------------- 130 | // whereString 131 | // 132 | // 133 | + (NSArray *)selectObjects:(Class)cls fromTable:(NSString *)tableName where:(NSString *)whereString withParams:(NSArray *)params orderBy:(NSString *)obString withSortType:(NSString *)type withRange:(NSRange)range { 134 | 135 | NSMutableArray *arr = [NSMutableArray array]; 136 | 137 | NSString *selectSQL = [GXSQLStatementManager select:tableName where:whereString orderBy:obString sortType:type limit:range]; 138 | 139 | FMResultSet *rs = [database executeQuery:selectSQL withArgumentsInArray:params]; 140 | 141 | if (!rs) { 142 | #if ENABLED_SQL_ERROR_LOG 143 | NSLog(@"DB SELECT TABLE %@(%@)", tableName, [database lastErrorMessage]); 144 | #endif 145 | } 146 | 147 | // 通过Class获取类成员名及成员类型 148 | NSArray *members = [[GXCache defaultCache] memberListByClass:cls]; 149 | 150 | while (rs.next) { 151 | 152 | id item = [[cls alloc] init]; 153 | 154 | [members enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 155 | 156 | if ([obj isKindOfClass:[NSDictionary class]]) { 157 | 158 | NSString *mName = obj[kKeyMemberName]; 159 | id value = [GXDatabaseManager valueForDictionary:obj inFMResutSet:rs]; 160 | if (value) { 161 | [item setValue:value forKey:mName]; 162 | } 163 | } 164 | }]; 165 | 166 | [arr addObject:item]; 167 | } 168 | 169 | return arr; 170 | } 171 | 172 | // 173 | // 174 | // example: SELECT COUNT(*) AS rowcount FROM film WHERE _shedualTime > ? AND _bShedualSms = ? AND _sendStatus = ? 175 | // 176 | + (NSInteger)selectCountFrom:(NSString *)tableName where:(NSString *)whereString withParams:(NSArray *)params { 177 | 178 | NSString *selectCountSQL = [GXSQLStatementManager selectCount:tableName where:whereString]; 179 | 180 | FMResultSet *rs = [database executeQuery:selectCountSQL withArgumentsInArray:params]; 181 | 182 | if (!rs) { 183 | #if ENABLED_SQL_ERROR_LOG 184 | NSLog(@"DB SELECT COUNT %@(%@)", tableName, [database lastErrorMessage]); 185 | #endif 186 | } 187 | 188 | while (rs.next) { 189 | NSInteger rowCount = [rs intForColumn:@"rowcount"]; 190 | return rowCount; 191 | } 192 | 193 | return 0; 194 | } 195 | 196 | 197 | + (BOOL)deleteTable:(NSString *)tableName where:(NSString *)whereString withParams:(NSArray *)params { 198 | 199 | NSString *deleteSQL = [GXSQLStatementManager delete:tableName where:whereString]; 200 | BOOL res = [database executeUpdate:deleteSQL withArgumentsInArray:params]; 201 | 202 | if (!res) { 203 | #if ENABLED_SQL_ERROR_LOG 204 | NSLog(@"DB DELETE TABLE %@(%@)", tableName, [database lastErrorMessage]); 205 | #endif 206 | } 207 | return res; 208 | } 209 | 210 | #pragma mark - Utils 211 | + (id)valueForDictionary:(NSDictionary *)dict inFMResutSet:(FMResultSet *)rs { 212 | 213 | id value = nil; 214 | 215 | NSString *mName = dict[kKeyMemberName]; 216 | NSString *mType = dict[kKeyMemberType]; 217 | 218 | if ([mType isEqualToString:StringWithUTF8String(kObjC_BOOL)] || 219 | [mType isEqualToString:StringWithUTF8String(kObjC_BOOL_iOS8)]) { 220 | 221 | BOOL bVal = [rs boolForColumn:mName]; 222 | value = @(bVal); 223 | 224 | } else if ([mType isEqualToString:StringWithUTF8String(kObjC_CGFloat)] || 225 | [mType isEqualToString:StringWithUTF8String(kObjC_Double)]) { 226 | 227 | double f = [rs doubleForColumn:mName]; 228 | value = @(f); 229 | 230 | } else if ([mType isEqualToString:StringWithUTF8String(kObjC_Enum_iOS8)]) { 231 | 232 | NSUInteger u = [rs longForColumn:mName]; 233 | value = @(u); 234 | 235 | } else if ([mType isEqualToString:StringWithUTF8String(kObjC_Long_long)]) { 236 | 237 | long long ll = [rs longLongIntForColumn:mName]; 238 | value = @(ll); 239 | 240 | } else if ([mType isEqualToString:StringWithUTF8String(kObjC_NSInteger)]) { 241 | 242 | NSInteger i = [rs intForColumn:mName]; 243 | value = @(i); 244 | 245 | } else if ([mType isEqualToString:StringWithUTF8String(kObjC_NSString)]) { 246 | 247 | value = [rs objectForColumnName:mName]; 248 | 249 | } else if ([mType isEqualToString:StringWithUTF8String(kObjC_Unsigned_Int)]) { 250 | 251 | unsigned int ui = [rs intForColumn:mName]; 252 | value = @(ui); 253 | 254 | } else { 255 | 256 | } 257 | 258 | return value; 259 | } 260 | 261 | 262 | @end 263 | -------------------------------------------------------------------------------- /DBDemo/Classes/GXHeader.h: -------------------------------------------------------------------------------- 1 | // 2 | // GXHeader.h 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #ifndef DBDemo_GXHeader_h 10 | #define DBDemo_GXHeader_h 11 | 12 | // 打印sql语句 13 | #define ENABLED_SQL_STATEMENT 1 14 | // 打印错误日志 15 | #define ENABLED_SQL_ERROR_LOG 1 16 | 17 | 18 | #define kObjC_BOOL "c" // BOOL 19 | #define kObjC_Unsigned_Int "I" // unsigned int 20 | #define kObjC_NSInteger "i" // int 21 | #define kObjC_Long_long "q" // long long 22 | #define kObjC_CGFloat "f" // float 23 | #define kObjC_Double "d" // double 24 | #define kObjC_NSString "@\"NSString\"" // NSString 25 | 26 | #define kObjC_BOOL_iOS8 "B" 27 | #define kObjC_Enum_iOS8 "Q" 28 | // 29 | // NULL: a NULL value 30 | // NUMERIC: a NUMERIC column, the storage class of the text is converted to INTEGER or REAL 31 | // REAL: an 8-byte IEEE floating point number. 32 | // BLOB: a blob of data 33 | // 34 | #define kSqlite_BOOL "INTEGER" 35 | #define kSqlite_Unsigned_Int "INTEGER" 36 | #define kSqlite_Integer "INTEGER" 37 | #define kSqlite_Long_long "INTEGER" 38 | #define kSqlite_CGFloat "FLOAT" 39 | #define kSqlite_Double "DOUBLE" 40 | #define kSqlite_NSString "TEXT" 41 | 42 | 43 | typedef struct _ObjCSqliteTypeMap { 44 | 45 | const char *objCType; 46 | const char *sqliteType; 47 | const char *typeDescription; 48 | 49 | } ObjCSqliteTypeMap; 50 | 51 | 52 | #define kKeyMemberName @"memberName" 53 | #define kKeyMemberType @"memberType" 54 | #define kKeySqliteType @"sqliteType" 55 | 56 | #define StringWithUTF8String(s) [NSString stringWithUTF8String:s] 57 | 58 | // 59 | // compare: LIKE, NOT LIKE, >, <, >=, <=, = 60 | // 61 | #define kWhereString(name, compare) [NSString stringWithFormat:@"%@ %@ ?", name, compare] 62 | 63 | // 64 | // logic: AND, OR 65 | // 66 | #define kWhereCombination(n1, logic, n2) [NSString stringWithFormat:@"%@ %@ %@", n1, logic, n2] 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /DBDemo/Classes/GXSQLStatementManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // GXSQLStatementManager.h 3 | // DBManager 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "GXHeader.h" 11 | 12 | 13 | @interface GXSQLStatementManager : NSObject 14 | 15 | + (NSString *)create:(NSString *)tableName withClass:(Class)cls withPrimaryKey:(NSString *)primaryKey; 16 | 17 | + (NSString *)replaceInto:(NSString *)tableName withParameterList:(NSString *) paramList; 18 | 19 | + (NSString *)select:(NSString *)tableName where:(NSString *)whereString orderBy:(NSString *)obString sortType:(NSString *)sType limit:(NSRange)range; 20 | + (NSString *)selectCount:(NSString *)tableName where:(NSString *)whereString; 21 | 22 | + (NSString *)update:(NSString *)tableName set:(NSArray *)params where:(NSString *)whereString; 23 | 24 | + (NSString *)delete:(NSString *)tableName where:(NSString *)whereString; 25 | 26 | + (NSString *)sqlTypeWithMemberType:(NSString *)mType; 27 | @end 28 | -------------------------------------------------------------------------------- /DBDemo/Classes/GXSQLStatementManager.m: -------------------------------------------------------------------------------- 1 | // 2 | // GXSQLStatementManager.m 3 | // DBManager 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import "GXSQLStatementManager.h" 10 | #import 11 | #import "NSObject+serializable.h" 12 | #import "GXCache.h" 13 | 14 | 15 | /* 16 | * 支持的数据类型 17 | * 18 | */ 19 | static ObjCSqliteTypeMap ObjCSqliteTypeMapTable[] = { 20 | 21 | {kObjC_BOOL, kSqlite_BOOL, "objc的BOOL类型"}, 22 | {kObjC_Unsigned_Int, kSqlite_Unsigned_Int, "unsigned int 无符号整形"}, 23 | {kObjC_NSInteger, kSqlite_Integer, "NSInteger 整形"}, 24 | {kObjC_Long_long, kSqlite_Long_long, "long long 64位整形"}, 25 | {kObjC_CGFloat, kSqlite_CGFloat, "CGFloat 单精度浮点型"}, 26 | {kObjC_Double, kSqlite_Double, "double 双精度浮点型"}, 27 | {kObjC_NSString, kSqlite_NSString, "NSString objc字符串"}, 28 | 29 | {kObjC_BOOL_iOS8, kSqlite_BOOL, "ios8中BOOL类型的编码,和之前版本有差别"}, 30 | {kObjC_Enum_iOS8, kSqlite_Long_long, "iOS8中枚举类型的编码,和之前版本有差别"} 31 | }; 32 | 33 | 34 | #define ObjCSqliteTypeMapSize sizeof(ObjCSqliteTypeMapTable)/sizeof(ObjCSqliteTypeMapTable[0]) 35 | 36 | 37 | @implementation GXSQLStatementManager 38 | 39 | // 40 | // 根据tableName、cls、primaryKey生成创建表的sql语句 41 | // 42 | // @"CREATE TABLE IF NOT EXISTS MyTable(aa FLOAT PRIMARY KEY,bb TEXT,cc INTEGER,dd INTEGER,ee TEXT) 43 | // 44 | + (NSString *)create:(NSString *)tableName withClass:(Class)cls withPrimaryKey:(NSString *)primaryKey { 45 | 46 | NSArray *members = [[GXCache defaultCache] memberListByClass:cls]; 47 | 48 | __block NSMutableString *sql = [NSMutableString string]; 49 | [members enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 50 | 51 | if ([obj isKindOfClass:[NSDictionary class]]) { 52 | 53 | NSString *mName = obj[kKeyMemberName]; 54 | NSString *sType = obj[kKeySqliteType]; 55 | 56 | NSString *sqlSection = [NSString stringWithFormat:@"%@ %@", mName, sType]; 57 | 58 | if ([primaryKey isEqualToString:mName]) { 59 | sqlSection = [sqlSection stringByAppendingString:@" PRIMARY KEY"]; 60 | } 61 | 62 | [sql appendString:sqlSection]; 63 | 64 | if (idx < members.count - 1) { 65 | [sql appendString:@","]; 66 | } 67 | } 68 | }]; 69 | 70 | NSString *createSQL = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@)", tableName, sql]; 71 | #if ENABLED_SQL_STATEMENT 72 | NSLog(@"SQL CREATE:%@", createSQL); 73 | #endif 74 | return createSQL; 75 | } 76 | 77 | 78 | + (NSString *) replaceInto:(NSString *)tableName withParameterList:(NSString *) paramList { 79 | 80 | NSString *replaceIntoSQL = [NSString stringWithFormat:@"REPLACE INTO %@ VALUES(%@)", tableName, paramList]; 81 | #if ENABLED_SQL_STATEMENT 82 | NSLog(@"SQL REPLACE INTO:%@", replaceIntoSQL); 83 | #endif 84 | return replaceIntoSQL; 85 | } 86 | 87 | 88 | /** 89 | * @brief 查询数据库 90 | * 91 | * @param tableName 表名 92 | * @param whereString where子句 93 | * @param obString order by字段 94 | * @param sType 排序类型: DESC or ASC 95 | * @param range 查找范围 96 | * 97 | * @return 返回查询sql 98 | */ 99 | + (NSString *) select:(NSString *)tableName where:(NSString *)whereString orderBy:(NSString *)obString sortType:(NSString *)sType limit:(NSRange)range 100 | { 101 | 102 | NSMutableString *selectSQL = [NSMutableString stringWithFormat:@"SELECT * FROM %@ WHERE ", tableName]; 103 | [selectSQL appendString:whereString]; 104 | 105 | if (obString.length > 0) { 106 | [selectSQL appendString:[NSString stringWithFormat:@" ORDER BY %@ %@ ", obString, sType]]; 107 | } 108 | 109 | if (range.length > 0) { 110 | [selectSQL appendString:[NSString stringWithFormat:@" LIMIT %lu", (unsigned long)range.length]]; 111 | } 112 | 113 | #if ENABLED_SQL_STATEMENT 114 | NSLog(@"SQL SELECT:%@", selectSQL); 115 | #endif 116 | return selectSQL; 117 | } 118 | 119 | + (NSString *)selectCount:(NSString *)tableName where:(NSString *)whereString { 120 | 121 | NSString *selectCountSQL = [NSString stringWithFormat:@"SELECT COUNT(*) AS rowcount FROM %@ WHERE %@", tableName, whereString]; 122 | 123 | #if ENABLED_SQL_STATEMENT 124 | NSLog(@"SQL SELECT COUNT:%@", selectCountSQL); 125 | #endif 126 | return selectCountSQL; 127 | } 128 | 129 | // 130 | // 修改表名: alter table department rename to dept; 131 | // 132 | // 133 | + (NSString *)rename:(NSString *)tableName to:(NSString *)newTableName { 134 | 135 | NSString *alterSQL = [NSString stringWithFormat:@"ALTER TABLE %@ RENAME TO %@", tableName, newTableName]; 136 | #if ENABLED_SQL_STATEMENT 137 | NSLog(@"SQL ALTER:%@", alterSQL); 138 | #endif 139 | return alterSQL; 140 | } 141 | 142 | // 143 | // 添加一列:alter table employee add column deptid integer; 144 | // 145 | // 146 | 147 | 148 | // 149 | // 更新数据:update employee set title='Sales Manager' where empid=104; 150 | // update student_info set stu_no=0001, name=hence where stu_no=0001; 151 | // 152 | + (NSString *)update:(NSString *)tableName set:(NSArray *)params where:(NSString *)whereString { 153 | 154 | if (0 == params.count || 0 == whereString.length) { 155 | return nil; 156 | } 157 | 158 | NSMutableString *updateSQL = [NSMutableString stringWithFormat:@"UPDATE %@ SET ", tableName]; 159 | 160 | NSMutableString *paramString = [NSMutableString string]; 161 | [params enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 162 | 163 | if ([obj isKindOfClass:[NSString class]]) { 164 | 165 | [paramString appendFormat:@"%@ = ?", obj]; 166 | if (idx != params.count - 1) { 167 | [paramString appendString:@","]; 168 | } 169 | } 170 | }]; 171 | 172 | [updateSQL appendFormat:@"%@ WHERE %@", paramString, whereString]; 173 | 174 | #if ENABLED_SQL_STATEMENT 175 | NSLog(@"SQL UPDATE:%@", updateSQL); 176 | #endif 177 | return updateSQL; 178 | } 179 | 180 | // 181 | // 删除数据: delete from student_info where stu_no=0001; 182 | // 183 | // 184 | + (NSString *)delete:(NSString *)tableName where:(NSString *)whereString { 185 | 186 | NSMutableString *deleteSQL = [NSMutableString stringWithFormat:@"DELETE FROM %@ ", tableName]; 187 | 188 | if (whereString) { 189 | [deleteSQL appendFormat:@" WHERE %@", whereString]; 190 | } 191 | 192 | #if ENABLED_SQL_STATEMENT 193 | NSLog(@"SQL DELETE:%@", deleteSQL); 194 | #endif 195 | return deleteSQL; 196 | } 197 | 198 | // 199 | // 创建索引:create index index_name on table_name(field); 200 | // create index student_index on student_table(stu_no); 201 | // 202 | // 203 | + (NSString *)createIndex:(NSString *)indexName onTable:(NSString *)tableName withColumn:(NSString *)field { 204 | 205 | NSString *creatIndexSQL = [NSString stringWithFormat:@"CREATE INDEX %@ on %@(%@)", indexName, tableName, field]; 206 | 207 | #if ENABLED_SQL_STATEMENT 208 | NSLog(@"SQL CREATE INDEX:%@", creatIndexSQL); 209 | #endif 210 | return creatIndexSQL; 211 | } 212 | 213 | #pragma mark - Utils memthods 214 | + (NSString *)sqlTypeWithMemberType:(NSString *)mType { 215 | 216 | const char *type = mType.UTF8String; 217 | 218 | for (int i = 0; i < ObjCSqliteTypeMapSize; i++) { 219 | 220 | const char *objcType = ObjCSqliteTypeMapTable[i].objCType; 221 | 222 | if (0 == strcmp(objcType, type)) { 223 | 224 | const char* sType = ObjCSqliteTypeMapTable[i].sqliteType; 225 | NSString *sqlType = [NSString stringWithUTF8String:sType]; 226 | 227 | return sqlType; 228 | } 229 | } 230 | 231 | return nil; 232 | } 233 | 234 | 235 | @end 236 | -------------------------------------------------------------------------------- /DBDemo/Classes/NSObject+serializable.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSObject+serializable.h 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | #import "GXHeader.h" 12 | #import "GXCache.h" 13 | 14 | @interface NSObject (serializable) 15 | 16 | - (NSMutableDictionary *)dictionary; 17 | 18 | + (NSString *)memberNameWithIvars:(Ivar *)vars atIndex:(NSInteger) index; 19 | + (NSString *)memberTypeWithIvars:(Ivar *) vars atIndex:(NSInteger) index; 20 | 21 | @end 22 | -------------------------------------------------------------------------------- /DBDemo/Classes/NSObject+serializable.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSObject+serializable.m 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import "NSObject+serializable.h" 10 | 11 | @implementation NSObject (serializable) 12 | 13 | - (NSMutableDictionary *)dictionary { 14 | 15 | NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 16 | 17 | Class cls = [self class]; 18 | NSArray *arr = [[GXCache defaultCache] memberListByClass:cls]; 19 | 20 | [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 21 | 22 | if ([obj isKindOfClass:[NSDictionary class]]) { 23 | 24 | NSString *mName = obj[kKeyMemberName]; 25 | NSString *mType = obj[kKeyMemberType]; 26 | id mValue = [self valueForKey:mName]; 27 | 28 | if (!mValue && [mType isEqualToString:[NSString stringWithFormat:@"%s", kObjC_NSString]]) { 29 | mValue = @""; 30 | } 31 | 32 | [dict setObject:mValue forKey:mName]; 33 | } 34 | }]; 35 | 36 | return dict; 37 | } 38 | 39 | #pragma mark - Utils 40 | + (NSString *)memberNameWithIvars:(Ivar *)vars atIndex:(NSInteger) index { 41 | 42 | const char *name = ivar_getName(vars[index]); 43 | NSString *mName = [NSString stringWithFormat:@"%s", name]; 44 | 45 | return mName; 46 | } 47 | 48 | 49 | + (NSString *)memberTypeWithIvars:(Ivar *) vars atIndex:(NSInteger) index { 50 | 51 | const char *type = ivar_getTypeEncoding(vars[index]); 52 | NSString *mType = [NSString stringWithFormat:@"%s", type]; 53 | 54 | return mType; 55 | } 56 | 57 | @end 58 | -------------------------------------------------------------------------------- /DBDemo/DBDemo.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | CB1D863A19CEAB820025052A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D863919CEAB820025052A /* main.m */; }; 11 | CB1D863D19CEAB820025052A /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D863C19CEAB820025052A /* AppDelegate.m */; }; 12 | CB1D864019CEAB820025052A /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D863F19CEAB820025052A /* ViewController.m */; }; 13 | CB1D864519CEAB820025052A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = CB1D864419CEAB820025052A /* Images.xcassets */; }; 14 | CB1D865419CEAB820025052A /* DBDemoTests.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D865319CEAB820025052A /* DBDemoTests.m */; }; 15 | CB1D867519CEABD80025052A /* GXMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D865F19CEABD80025052A /* GXMessage.m */; }; 16 | CB1D867619CEABD80025052A /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D866219CEABD80025052A /* FMDatabase.m */; }; 17 | CB1D867719CEABD80025052A /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D866419CEABD80025052A /* FMDatabaseAdditions.m */; }; 18 | CB1D867819CEABD80025052A /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D866619CEABD80025052A /* FMDatabasePool.m */; }; 19 | CB1D867919CEABD80025052A /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D866819CEABD80025052A /* FMDatabaseQueue.m */; }; 20 | CB1D867A19CEABD80025052A /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CB1D866B19CEABD80025052A /* FMResultSet.m */; }; 21 | CB1D867B19CEABD80025052A /* db.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = CB1D866D19CEABD80025052A /* db.sqlite */; }; 22 | CB1D868019CEABF30025052A /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = CB1D867F19CEABF30025052A /* libsqlite3.dylib */; }; 23 | CB8560FE19D114FD00B67244 /* iphone-512.png in Resources */ = {isa = PBXBuildFile; fileRef = CB8560FD19D114FD00B67244 /* iphone-512.png */; }; 24 | CB85610219D117B500B67244 /* iphone-25.png in Resources */ = {isa = PBXBuildFile; fileRef = CB85610119D117B500B67244 /* iphone-25.png */; }; 25 | CB85610419D1183200B67244 /* iphone-25@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = CB85610319D1183200B67244 /* iphone-25@2x.png */; }; 26 | CBB128D11CBCFF2400567680 /* GXCache.m in Sources */ = {isa = PBXBuildFile; fileRef = CBB128C91CBCFF2400567680 /* GXCache.m */; }; 27 | CBB128D21CBCFF2400567680 /* GXDatabaseManager.m in Sources */ = {isa = PBXBuildFile; fileRef = CBB128CB1CBCFF2400567680 /* GXDatabaseManager.m */; }; 28 | CBB128D31CBCFF2400567680 /* GXSQLStatementManager.m in Sources */ = {isa = PBXBuildFile; fileRef = CBB128CE1CBCFF2400567680 /* GXSQLStatementManager.m */; }; 29 | CBB128D41CBCFF2400567680 /* NSObject+serializable.m in Sources */ = {isa = PBXBuildFile; fileRef = CBB128D01CBCFF2400567680 /* NSObject+serializable.m */; }; 30 | CBE12C9319D7F16A002ABB40 /* GXMessageDBEntity.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE12C9219D7F16A002ABB40 /* GXMessageDBEntity.m */; }; 31 | /* End PBXBuildFile section */ 32 | 33 | /* Begin PBXContainerItemProxy section */ 34 | CB1D864E19CEAB820025052A /* PBXContainerItemProxy */ = { 35 | isa = PBXContainerItemProxy; 36 | containerPortal = CB1D862C19CEAB820025052A /* Project object */; 37 | proxyType = 1; 38 | remoteGlobalIDString = CB1D863319CEAB820025052A; 39 | remoteInfo = DBDemo; 40 | }; 41 | /* End PBXContainerItemProxy section */ 42 | 43 | /* Begin PBXFileReference section */ 44 | CB1D863419CEAB820025052A /* DBDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DBDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; 45 | CB1D863819CEAB820025052A /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 46 | CB1D863919CEAB820025052A /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 47 | CB1D863B19CEAB820025052A /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 48 | CB1D863C19CEAB820025052A /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 49 | CB1D863E19CEAB820025052A /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; 50 | CB1D863F19CEAB820025052A /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 51 | CB1D864419CEAB820025052A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; 52 | CB1D864D19CEAB820025052A /* DBDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DBDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 53 | CB1D865219CEAB820025052A /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 54 | CB1D865319CEAB820025052A /* DBDemoTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = DBDemoTests.m; sourceTree = ""; }; 55 | CB1D865E19CEABD80025052A /* GXMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GXMessage.h; sourceTree = ""; }; 56 | CB1D865F19CEABD80025052A /* GXMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GXMessage.m; sourceTree = ""; }; 57 | CB1D866119CEABD80025052A /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = ""; }; 58 | CB1D866219CEABD80025052A /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabase.m; sourceTree = ""; }; 59 | CB1D866319CEABD80025052A /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseAdditions.h; sourceTree = ""; }; 60 | CB1D866419CEABD80025052A /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditions.m; sourceTree = ""; }; 61 | CB1D866519CEABD80025052A /* FMDatabasePool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabasePool.h; sourceTree = ""; }; 62 | CB1D866619CEABD80025052A /* FMDatabasePool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePool.m; sourceTree = ""; }; 63 | CB1D866719CEABD80025052A /* FMDatabaseQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseQueue.h; sourceTree = ""; }; 64 | CB1D866819CEABD80025052A /* FMDatabaseQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueue.m; sourceTree = ""; }; 65 | CB1D866919CEABD80025052A /* FMDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDB.h; sourceTree = ""; }; 66 | CB1D866A19CEABD80025052A /* FMResultSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMResultSet.h; sourceTree = ""; }; 67 | CB1D866B19CEABD80025052A /* FMResultSet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMResultSet.m; sourceTree = ""; }; 68 | CB1D866D19CEABD80025052A /* db.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.sqlite; sourceTree = ""; }; 69 | CB1D867F19CEABF30025052A /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; }; 70 | CB8560FD19D114FD00B67244 /* iphone-512.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "iphone-512\U001e.png"; sourceTree = ""; }; 71 | CB85610119D117B500B67244 /* iphone-25.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "iphone-25.png"; sourceTree = ""; }; 72 | CB85610319D1183200B67244 /* iphone-25@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "iphone-25@2x.png"; sourceTree = ""; }; 73 | CBB128C81CBCFF2400567680 /* GXCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GXCache.h; sourceTree = ""; }; 74 | CBB128C91CBCFF2400567680 /* GXCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GXCache.m; sourceTree = ""; }; 75 | CBB128CA1CBCFF2400567680 /* GXDatabaseManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GXDatabaseManager.h; sourceTree = ""; }; 76 | CBB128CB1CBCFF2400567680 /* GXDatabaseManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GXDatabaseManager.m; sourceTree = ""; }; 77 | CBB128CC1CBCFF2400567680 /* GXHeader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GXHeader.h; sourceTree = ""; }; 78 | CBB128CD1CBCFF2400567680 /* GXSQLStatementManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GXSQLStatementManager.h; sourceTree = ""; }; 79 | CBB128CE1CBCFF2400567680 /* GXSQLStatementManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GXSQLStatementManager.m; sourceTree = ""; }; 80 | CBB128CF1CBCFF2400567680 /* NSObject+serializable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSObject+serializable.h"; sourceTree = ""; }; 81 | CBB128D01CBCFF2400567680 /* NSObject+serializable.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSObject+serializable.m"; sourceTree = ""; }; 82 | CBD5E26719CFFEA400097CD3 /* play.playground */ = {isa = PBXFileReference; lastKnownFileType = file.playground; path = play.playground; sourceTree = ""; }; 83 | CBE12C9119D7F16A002ABB40 /* GXMessageDBEntity.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GXMessageDBEntity.h; sourceTree = ""; }; 84 | CBE12C9219D7F16A002ABB40 /* GXMessageDBEntity.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GXMessageDBEntity.m; sourceTree = ""; }; 85 | /* End PBXFileReference section */ 86 | 87 | /* Begin PBXFrameworksBuildPhase section */ 88 | CB1D863119CEAB820025052A /* Frameworks */ = { 89 | isa = PBXFrameworksBuildPhase; 90 | buildActionMask = 2147483647; 91 | files = ( 92 | CB1D868019CEABF30025052A /* libsqlite3.dylib in Frameworks */, 93 | ); 94 | runOnlyForDeploymentPostprocessing = 0; 95 | }; 96 | CB1D864A19CEAB820025052A /* Frameworks */ = { 97 | isa = PBXFrameworksBuildPhase; 98 | buildActionMask = 2147483647; 99 | files = ( 100 | ); 101 | runOnlyForDeploymentPostprocessing = 0; 102 | }; 103 | /* End PBXFrameworksBuildPhase section */ 104 | 105 | /* Begin PBXGroup section */ 106 | CB1D862B19CEAB820025052A = { 107 | isa = PBXGroup; 108 | children = ( 109 | CB1D867F19CEABF30025052A /* libsqlite3.dylib */, 110 | CB1D863619CEAB820025052A /* DBDemo */, 111 | CB1D865019CEAB820025052A /* DBDemoTests */, 112 | CB1D863519CEAB820025052A /* Products */, 113 | ); 114 | sourceTree = ""; 115 | }; 116 | CB1D863519CEAB820025052A /* Products */ = { 117 | isa = PBXGroup; 118 | children = ( 119 | CB1D863419CEAB820025052A /* DBDemo.app */, 120 | CB1D864D19CEAB820025052A /* DBDemoTests.xctest */, 121 | ); 122 | name = Products; 123 | sourceTree = ""; 124 | }; 125 | CB1D863619CEAB820025052A /* DBDemo */ = { 126 | isa = PBXGroup; 127 | children = ( 128 | CBB128C71CBCFF2400567680 /* Classes */, 129 | CB1D865D19CEABD80025052A /* DataModel */, 130 | CB1D866019CEABD80025052A /* fmdb */, 131 | CB1D866C19CEABD80025052A /* resource */, 132 | CB1D863B19CEAB820025052A /* AppDelegate.h */, 133 | CB1D863C19CEAB820025052A /* AppDelegate.m */, 134 | CB1D863E19CEAB820025052A /* ViewController.h */, 135 | CB1D863F19CEAB820025052A /* ViewController.m */, 136 | CB1D864419CEAB820025052A /* Images.xcassets */, 137 | CB1D863719CEAB820025052A /* Supporting Files */, 138 | CBD5E26719CFFEA400097CD3 /* play.playground */, 139 | ); 140 | path = DBDemo; 141 | sourceTree = ""; 142 | }; 143 | CB1D863719CEAB820025052A /* Supporting Files */ = { 144 | isa = PBXGroup; 145 | children = ( 146 | CB1D863819CEAB820025052A /* Info.plist */, 147 | CB1D863919CEAB820025052A /* main.m */, 148 | ); 149 | name = "Supporting Files"; 150 | sourceTree = ""; 151 | }; 152 | CB1D865019CEAB820025052A /* DBDemoTests */ = { 153 | isa = PBXGroup; 154 | children = ( 155 | CB1D865319CEAB820025052A /* DBDemoTests.m */, 156 | CB1D865119CEAB820025052A /* Supporting Files */, 157 | ); 158 | path = DBDemoTests; 159 | sourceTree = ""; 160 | }; 161 | CB1D865119CEAB820025052A /* Supporting Files */ = { 162 | isa = PBXGroup; 163 | children = ( 164 | CB1D865219CEAB820025052A /* Info.plist */, 165 | ); 166 | name = "Supporting Files"; 167 | sourceTree = ""; 168 | }; 169 | CB1D865D19CEABD80025052A /* DataModel */ = { 170 | isa = PBXGroup; 171 | children = ( 172 | CBE12C9119D7F16A002ABB40 /* GXMessageDBEntity.h */, 173 | CBE12C9219D7F16A002ABB40 /* GXMessageDBEntity.m */, 174 | CB1D865E19CEABD80025052A /* GXMessage.h */, 175 | CB1D865F19CEABD80025052A /* GXMessage.m */, 176 | ); 177 | path = DataModel; 178 | sourceTree = ""; 179 | }; 180 | CB1D866019CEABD80025052A /* fmdb */ = { 181 | isa = PBXGroup; 182 | children = ( 183 | CB1D866119CEABD80025052A /* FMDatabase.h */, 184 | CB1D866219CEABD80025052A /* FMDatabase.m */, 185 | CB1D866319CEABD80025052A /* FMDatabaseAdditions.h */, 186 | CB1D866419CEABD80025052A /* FMDatabaseAdditions.m */, 187 | CB1D866519CEABD80025052A /* FMDatabasePool.h */, 188 | CB1D866619CEABD80025052A /* FMDatabasePool.m */, 189 | CB1D866719CEABD80025052A /* FMDatabaseQueue.h */, 190 | CB1D866819CEABD80025052A /* FMDatabaseQueue.m */, 191 | CB1D866919CEABD80025052A /* FMDB.h */, 192 | CB1D866A19CEABD80025052A /* FMResultSet.h */, 193 | CB1D866B19CEABD80025052A /* FMResultSet.m */, 194 | ); 195 | path = fmdb; 196 | sourceTree = ""; 197 | }; 198 | CB1D866C19CEABD80025052A /* resource */ = { 199 | isa = PBXGroup; 200 | children = ( 201 | CB85610319D1183200B67244 /* iphone-25@2x.png */, 202 | CB85610119D117B500B67244 /* iphone-25.png */, 203 | CB8560FD19D114FD00B67244 /* iphone-512.png */, 204 | CB1D866D19CEABD80025052A /* db.sqlite */, 205 | ); 206 | path = resource; 207 | sourceTree = ""; 208 | }; 209 | CBB128C71CBCFF2400567680 /* Classes */ = { 210 | isa = PBXGroup; 211 | children = ( 212 | CBB128C81CBCFF2400567680 /* GXCache.h */, 213 | CBB128C91CBCFF2400567680 /* GXCache.m */, 214 | CBB128CA1CBCFF2400567680 /* GXDatabaseManager.h */, 215 | CBB128CB1CBCFF2400567680 /* GXDatabaseManager.m */, 216 | CBB128CC1CBCFF2400567680 /* GXHeader.h */, 217 | CBB128CD1CBCFF2400567680 /* GXSQLStatementManager.h */, 218 | CBB128CE1CBCFF2400567680 /* GXSQLStatementManager.m */, 219 | CBB128CF1CBCFF2400567680 /* NSObject+serializable.h */, 220 | CBB128D01CBCFF2400567680 /* NSObject+serializable.m */, 221 | ); 222 | path = Classes; 223 | sourceTree = SOURCE_ROOT; 224 | }; 225 | /* End PBXGroup section */ 226 | 227 | /* Begin PBXNativeTarget section */ 228 | CB1D863319CEAB820025052A /* DBDemo */ = { 229 | isa = PBXNativeTarget; 230 | buildConfigurationList = CB1D865719CEAB820025052A /* Build configuration list for PBXNativeTarget "DBDemo" */; 231 | buildPhases = ( 232 | CB1D863019CEAB820025052A /* Sources */, 233 | CB1D863119CEAB820025052A /* Frameworks */, 234 | CB1D863219CEAB820025052A /* Resources */, 235 | ); 236 | buildRules = ( 237 | ); 238 | dependencies = ( 239 | ); 240 | name = DBDemo; 241 | productName = DBDemo; 242 | productReference = CB1D863419CEAB820025052A /* DBDemo.app */; 243 | productType = "com.apple.product-type.application"; 244 | }; 245 | CB1D864C19CEAB820025052A /* DBDemoTests */ = { 246 | isa = PBXNativeTarget; 247 | buildConfigurationList = CB1D865A19CEAB820025052A /* Build configuration list for PBXNativeTarget "DBDemoTests" */; 248 | buildPhases = ( 249 | CB1D864919CEAB820025052A /* Sources */, 250 | CB1D864A19CEAB820025052A /* Frameworks */, 251 | CB1D864B19CEAB820025052A /* Resources */, 252 | ); 253 | buildRules = ( 254 | ); 255 | dependencies = ( 256 | CB1D864F19CEAB820025052A /* PBXTargetDependency */, 257 | ); 258 | name = DBDemoTests; 259 | productName = DBDemoTests; 260 | productReference = CB1D864D19CEAB820025052A /* DBDemoTests.xctest */; 261 | productType = "com.apple.product-type.bundle.unit-test"; 262 | }; 263 | /* End PBXNativeTarget section */ 264 | 265 | /* Begin PBXProject section */ 266 | CB1D862C19CEAB820025052A /* Project object */ = { 267 | isa = PBXProject; 268 | attributes = { 269 | LastUpgradeCheck = 0600; 270 | ORGANIZATIONNAME = Gerry; 271 | TargetAttributes = { 272 | CB1D863319CEAB820025052A = { 273 | CreatedOnToolsVersion = 6.0.1; 274 | }; 275 | CB1D864C19CEAB820025052A = { 276 | CreatedOnToolsVersion = 6.0.1; 277 | TestTargetID = CB1D863319CEAB820025052A; 278 | }; 279 | }; 280 | }; 281 | buildConfigurationList = CB1D862F19CEAB820025052A /* Build configuration list for PBXProject "DBDemo" */; 282 | compatibilityVersion = "Xcode 3.2"; 283 | developmentRegion = English; 284 | hasScannedForEncodings = 0; 285 | knownRegions = ( 286 | English, 287 | en, 288 | Base, 289 | ); 290 | mainGroup = CB1D862B19CEAB820025052A; 291 | productRefGroup = CB1D863519CEAB820025052A /* Products */; 292 | projectDirPath = ""; 293 | projectRoot = ""; 294 | targets = ( 295 | CB1D863319CEAB820025052A /* DBDemo */, 296 | CB1D864C19CEAB820025052A /* DBDemoTests */, 297 | ); 298 | }; 299 | /* End PBXProject section */ 300 | 301 | /* Begin PBXResourcesBuildPhase section */ 302 | CB1D863219CEAB820025052A /* Resources */ = { 303 | isa = PBXResourcesBuildPhase; 304 | buildActionMask = 2147483647; 305 | files = ( 306 | CB8560FE19D114FD00B67244 /* iphone-512.png in Resources */, 307 | CB1D864519CEAB820025052A /* Images.xcassets in Resources */, 308 | CB85610419D1183200B67244 /* iphone-25@2x.png in Resources */, 309 | CB1D867B19CEABD80025052A /* db.sqlite in Resources */, 310 | CB85610219D117B500B67244 /* iphone-25.png in Resources */, 311 | ); 312 | runOnlyForDeploymentPostprocessing = 0; 313 | }; 314 | CB1D864B19CEAB820025052A /* Resources */ = { 315 | isa = PBXResourcesBuildPhase; 316 | buildActionMask = 2147483647; 317 | files = ( 318 | ); 319 | runOnlyForDeploymentPostprocessing = 0; 320 | }; 321 | /* End PBXResourcesBuildPhase section */ 322 | 323 | /* Begin PBXSourcesBuildPhase section */ 324 | CB1D863019CEAB820025052A /* Sources */ = { 325 | isa = PBXSourcesBuildPhase; 326 | buildActionMask = 2147483647; 327 | files = ( 328 | CB1D864019CEAB820025052A /* ViewController.m in Sources */, 329 | CBB128D11CBCFF2400567680 /* GXCache.m in Sources */, 330 | CB1D867919CEABD80025052A /* FMDatabaseQueue.m in Sources */, 331 | CBB128D31CBCFF2400567680 /* GXSQLStatementManager.m in Sources */, 332 | CBB128D41CBCFF2400567680 /* NSObject+serializable.m in Sources */, 333 | CBE12C9319D7F16A002ABB40 /* GXMessageDBEntity.m in Sources */, 334 | CB1D867519CEABD80025052A /* GXMessage.m in Sources */, 335 | CB1D863D19CEAB820025052A /* AppDelegate.m in Sources */, 336 | CB1D867619CEABD80025052A /* FMDatabase.m in Sources */, 337 | CB1D867819CEABD80025052A /* FMDatabasePool.m in Sources */, 338 | CB1D867A19CEABD80025052A /* FMResultSet.m in Sources */, 339 | CBB128D21CBCFF2400567680 /* GXDatabaseManager.m in Sources */, 340 | CB1D863A19CEAB820025052A /* main.m in Sources */, 341 | CB1D867719CEABD80025052A /* FMDatabaseAdditions.m in Sources */, 342 | ); 343 | runOnlyForDeploymentPostprocessing = 0; 344 | }; 345 | CB1D864919CEAB820025052A /* Sources */ = { 346 | isa = PBXSourcesBuildPhase; 347 | buildActionMask = 2147483647; 348 | files = ( 349 | CB1D865419CEAB820025052A /* DBDemoTests.m in Sources */, 350 | ); 351 | runOnlyForDeploymentPostprocessing = 0; 352 | }; 353 | /* End PBXSourcesBuildPhase section */ 354 | 355 | /* Begin PBXTargetDependency section */ 356 | CB1D864F19CEAB820025052A /* PBXTargetDependency */ = { 357 | isa = PBXTargetDependency; 358 | target = CB1D863319CEAB820025052A /* DBDemo */; 359 | targetProxy = CB1D864E19CEAB820025052A /* PBXContainerItemProxy */; 360 | }; 361 | /* End PBXTargetDependency section */ 362 | 363 | /* Begin XCBuildConfiguration section */ 364 | CB1D865519CEAB820025052A /* Debug */ = { 365 | isa = XCBuildConfiguration; 366 | buildSettings = { 367 | ALWAYS_SEARCH_USER_PATHS = NO; 368 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 369 | CLANG_CXX_LIBRARY = "libc++"; 370 | CLANG_ENABLE_MODULES = YES; 371 | CLANG_ENABLE_OBJC_ARC = YES; 372 | CLANG_WARN_BOOL_CONVERSION = YES; 373 | CLANG_WARN_CONSTANT_CONVERSION = YES; 374 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 375 | CLANG_WARN_EMPTY_BODY = YES; 376 | CLANG_WARN_ENUM_CONVERSION = YES; 377 | CLANG_WARN_INT_CONVERSION = YES; 378 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 379 | CLANG_WARN_UNREACHABLE_CODE = YES; 380 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 381 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 382 | COPY_PHASE_STRIP = NO; 383 | ENABLE_STRICT_OBJC_MSGSEND = YES; 384 | GCC_C_LANGUAGE_STANDARD = gnu99; 385 | GCC_DYNAMIC_NO_PIC = NO; 386 | GCC_OPTIMIZATION_LEVEL = 0; 387 | GCC_PREPROCESSOR_DEFINITIONS = ( 388 | "DEBUG=1", 389 | "$(inherited)", 390 | ); 391 | GCC_SYMBOLS_PRIVATE_EXTERN = NO; 392 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 393 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 394 | GCC_WARN_UNDECLARED_SELECTOR = YES; 395 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 396 | GCC_WARN_UNUSED_FUNCTION = YES; 397 | GCC_WARN_UNUSED_VARIABLE = YES; 398 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 399 | MTL_ENABLE_DEBUG_INFO = YES; 400 | ONLY_ACTIVE_ARCH = YES; 401 | SDKROOT = iphoneos; 402 | }; 403 | name = Debug; 404 | }; 405 | CB1D865619CEAB820025052A /* Release */ = { 406 | isa = XCBuildConfiguration; 407 | buildSettings = { 408 | ALWAYS_SEARCH_USER_PATHS = NO; 409 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 410 | CLANG_CXX_LIBRARY = "libc++"; 411 | CLANG_ENABLE_MODULES = YES; 412 | CLANG_ENABLE_OBJC_ARC = YES; 413 | CLANG_WARN_BOOL_CONVERSION = YES; 414 | CLANG_WARN_CONSTANT_CONVERSION = YES; 415 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 416 | CLANG_WARN_EMPTY_BODY = YES; 417 | CLANG_WARN_ENUM_CONVERSION = YES; 418 | CLANG_WARN_INT_CONVERSION = YES; 419 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 420 | CLANG_WARN_UNREACHABLE_CODE = YES; 421 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 422 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 423 | COPY_PHASE_STRIP = YES; 424 | ENABLE_NS_ASSERTIONS = NO; 425 | ENABLE_STRICT_OBJC_MSGSEND = YES; 426 | GCC_C_LANGUAGE_STANDARD = gnu99; 427 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 428 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 429 | GCC_WARN_UNDECLARED_SELECTOR = YES; 430 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 431 | GCC_WARN_UNUSED_FUNCTION = YES; 432 | GCC_WARN_UNUSED_VARIABLE = YES; 433 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 434 | MTL_ENABLE_DEBUG_INFO = NO; 435 | SDKROOT = iphoneos; 436 | VALIDATE_PRODUCT = YES; 437 | }; 438 | name = Release; 439 | }; 440 | CB1D865819CEAB820025052A /* Debug */ = { 441 | isa = XCBuildConfiguration; 442 | buildSettings = { 443 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 444 | ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; 445 | INFOPLIST_FILE = DBDemo/Info.plist; 446 | IPHONEOS_DEPLOYMENT_TARGET = 6.0; 447 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 448 | PRODUCT_NAME = "$(TARGET_NAME)"; 449 | }; 450 | name = Debug; 451 | }; 452 | CB1D865919CEAB820025052A /* Release */ = { 453 | isa = XCBuildConfiguration; 454 | buildSettings = { 455 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 456 | ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; 457 | INFOPLIST_FILE = DBDemo/Info.plist; 458 | IPHONEOS_DEPLOYMENT_TARGET = 6.0; 459 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 460 | PRODUCT_NAME = "$(TARGET_NAME)"; 461 | }; 462 | name = Release; 463 | }; 464 | CB1D865B19CEAB820025052A /* Debug */ = { 465 | isa = XCBuildConfiguration; 466 | buildSettings = { 467 | BUNDLE_LOADER = "$(TEST_HOST)"; 468 | FRAMEWORK_SEARCH_PATHS = ( 469 | "$(SDKROOT)/Developer/Library/Frameworks", 470 | "$(inherited)", 471 | ); 472 | GCC_PREPROCESSOR_DEFINITIONS = ( 473 | "DEBUG=1", 474 | "$(inherited)", 475 | ); 476 | INFOPLIST_FILE = DBDemoTests/Info.plist; 477 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 478 | PRODUCT_NAME = "$(TARGET_NAME)"; 479 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/DBDemo.app/DBDemo"; 480 | }; 481 | name = Debug; 482 | }; 483 | CB1D865C19CEAB820025052A /* Release */ = { 484 | isa = XCBuildConfiguration; 485 | buildSettings = { 486 | BUNDLE_LOADER = "$(TEST_HOST)"; 487 | FRAMEWORK_SEARCH_PATHS = ( 488 | "$(SDKROOT)/Developer/Library/Frameworks", 489 | "$(inherited)", 490 | ); 491 | INFOPLIST_FILE = DBDemoTests/Info.plist; 492 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 493 | PRODUCT_NAME = "$(TARGET_NAME)"; 494 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/DBDemo.app/DBDemo"; 495 | }; 496 | name = Release; 497 | }; 498 | /* End XCBuildConfiguration section */ 499 | 500 | /* Begin XCConfigurationList section */ 501 | CB1D862F19CEAB820025052A /* Build configuration list for PBXProject "DBDemo" */ = { 502 | isa = XCConfigurationList; 503 | buildConfigurations = ( 504 | CB1D865519CEAB820025052A /* Debug */, 505 | CB1D865619CEAB820025052A /* Release */, 506 | ); 507 | defaultConfigurationIsVisible = 0; 508 | defaultConfigurationName = Release; 509 | }; 510 | CB1D865719CEAB820025052A /* Build configuration list for PBXNativeTarget "DBDemo" */ = { 511 | isa = XCConfigurationList; 512 | buildConfigurations = ( 513 | CB1D865819CEAB820025052A /* Debug */, 514 | CB1D865919CEAB820025052A /* Release */, 515 | ); 516 | defaultConfigurationIsVisible = 0; 517 | defaultConfigurationName = Release; 518 | }; 519 | CB1D865A19CEAB820025052A /* Build configuration list for PBXNativeTarget "DBDemoTests" */ = { 520 | isa = XCConfigurationList; 521 | buildConfigurations = ( 522 | CB1D865B19CEAB820025052A /* Debug */, 523 | CB1D865C19CEAB820025052A /* Release */, 524 | ); 525 | defaultConfigurationIsVisible = 0; 526 | defaultConfigurationName = Release; 527 | }; 528 | /* End XCConfigurationList section */ 529 | }; 530 | rootObject = CB1D862C19CEAB820025052A /* Project object */; 531 | } 532 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | #import "ViewController.h" 11 | 12 | @interface AppDelegate () 13 | 14 | @end 15 | 16 | @implementation AppDelegate 17 | 18 | 19 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 20 | // Override point for customization after application launch. 21 | 22 | self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 23 | ViewController *vc= [[ViewController alloc] init]; 24 | 25 | self.window.rootViewController = vc; 26 | [self.window makeKeyAndVisible]; 27 | return YES; 28 | } 29 | 30 | - (void)applicationWillResignActive:(UIApplication *)application { 31 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 32 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 33 | } 34 | 35 | - (void)applicationDidEnterBackground:(UIApplication *)application { 36 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 37 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 38 | } 39 | 40 | - (void)applicationWillEnterForeground:(UIApplication *)application { 41 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 42 | } 43 | 44 | - (void)applicationDidBecomeActive:(UIApplication *)application { 45 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 46 | } 47 | 48 | - (void)applicationWillTerminate:(UIApplication *)application { 49 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 50 | } 51 | 52 | @end 53 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/Base.lproj/LaunchScreen.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 20 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/DataModel/GXMessage.h: -------------------------------------------------------------------------------- 1 | // 2 | // GChatMessage.h 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-4. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | enum { 13 | EChatSessionUnKown = 0, 14 | EChatSessionNormal = 1, 15 | EChatSessionPgGroup = 2, 16 | EChatSessionDgGroup = 3, 17 | EChatSessionSystem = 4, 18 | EChatSessionPublicPlatform = 5 19 | }; 20 | typedef NSUInteger ChatSessionType; 21 | 22 | 23 | 24 | enum 25 | { 26 | EUnknownMessage = 0xFFFF, 27 | ETextMessage = 0, 28 | EPicMessage = 1, 29 | EMultiplepicMessage = 2, 30 | EAudioMessage = 3, 31 | EVedioMessage = 4, 32 | EAudiolinkMessage = 5, 33 | EVediolinkMessage = 6, 34 | EOutcardMessage = 7, 35 | ELocationMessage = 8, 36 | ECardMessage = 9, 37 | EEmotionMessage = 10, 38 | ESinglepictextMessage = 11, 39 | EMultpictextMessage = 12, 40 | EEmailMessage = 13, 41 | ECeTextMessage = 14, 42 | EGamelinkMessage = 15, 43 | EMixpictextMessage = 16, 44 | EHyperlinkMessage = 17, 45 | ETextlinkMessage = 18, 46 | ECeaudioMessage = 19, 47 | EReadbumobjMessage = 20, 48 | EPromptMessage = 21, 49 | EVideoPromptMessage = 22, 50 | EVoipPromptMessage = 23, 51 | EAudioChatPromptMessage = 24, 52 | ETimeMessage = 25, 53 | ECreateDGMessage = 26, 54 | }; 55 | typedef NSUInteger MessageType; 56 | 57 | enum 58 | { 59 | EThumbStateDownloading = 0, 60 | EThumbstateDownloaded = 1, 61 | }; 62 | typedef NSUInteger ThumbDownloadState; 63 | 64 | 65 | enum 66 | { 67 | EMessageStatusWaitForSend = 0, 68 | EMessageStatusSending = 1, 69 | EMessageStatusUploaded = 2, 70 | EMessageStatusSentOk = 3, 71 | EMessageStatusSendFail = 4, 72 | 73 | EMessageStatusRcvOk = 5, 74 | EMessageStatusDownloading = 6, 75 | EMessageStatusDownloadOk = 7, 76 | EMessageStatusDownloadFailed = 8, 77 | 78 | EMessageStatusTimeout 79 | 80 | }; 81 | typedef NSUInteger MessageStatus; 82 | 83 | enum{ 84 | EAVPromptOutSession = 0, 85 | EAVPromptInSession = 1, 86 | EAVPromptMiddle = 2, 87 | }; 88 | typedef NSUInteger EAVPromptType; 89 | 90 | // 4-1 91 | @interface GXBaseMessage : NSObject { 92 | 93 | NSString *address; 94 | } 95 | 96 | @property (nonatomic, assign) NSInteger count; 97 | @property (nonatomic, strong) NSString *name; 98 | @property (nonatomic, strong) NSMutableArray *datas; 99 | 100 | 101 | @end 102 | 103 | // 26-2 104 | @interface GXMessage : GXBaseMessage { 105 | 106 | // 3 107 | BOOL isReSendMessage; 108 | CGFloat cellHeight; 109 | NSMutableDictionary* thumbDownloadDictionary; 110 | 111 | } 112 | 113 | // 1 114 | @property(nonatomic, strong) NSString *company; 115 | 116 | // 5 117 | @property(nonatomic,strong)NSString* sessionUri; 118 | @property(nonatomic,strong)NSString* sessionUserid; 119 | @property(nonatomic,strong)NSString* speakerName; 120 | @property(nonatomic,strong)NSString* speakerUri; 121 | @property(nonatomic,strong)NSString* speakerUserID; 122 | 123 | // 6 124 | @property(nonatomic,strong)NSString* msgId; 125 | @property(nonatomic,strong)NSString* msgContent; 126 | @property(nonatomic,strong)NSString* originalContent; 127 | @property(nonatomic,strong)NSString* supportLists; 128 | @property(nonatomic,strong)NSString* fontName; 129 | @property(nonatomic,strong)NSString* rmsId; 130 | 131 | // 3 132 | @property(nonatomic,assign)long long rqMsgId; 133 | @property(nonatomic,assign)NSTimeInterval msgTime; 134 | @property(nonatomic,strong, readonly)NSMutableArray* elements; 135 | 136 | // 3 137 | @property(nonatomic,assign)ChatSessionType sessionType; 138 | @property(nonatomic,assign)MessageStatus status; 139 | @property(nonatomic,assign)EAVPromptType avPromptMsgType; 140 | 141 | // 5 142 | @property(nonatomic,assign)BOOL isReceive; 143 | @property(nonatomic,assign)BOOL isCC; 144 | @property(nonatomic,assign)BOOL bSending; 145 | @property(nonatomic,assign)BOOL isSmsMsg; 146 | @property(nonatomic,assign)BOOL isCloudBackupMsg; 147 | 148 | 149 | 150 | @end 151 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/DataModel/GXMessage.m: -------------------------------------------------------------------------------- 1 | // 2 | // GChatMessage.m 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-4. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import "GXMessage.h" 10 | 11 | @implementation GXBaseMessage 12 | 13 | @end 14 | 15 | @implementation GXMessage 16 | 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/DataModel/GXMessageDBEntity.h: -------------------------------------------------------------------------------- 1 | // 2 | // FtChatMessageDBEntity.h 3 | // FetionHDLogic 4 | // 5 | // Created by Gerry on 14-5-30. 6 | // Copyright (c) 2014年 GErry. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "GXMessage.h" 11 | 12 | @interface GXMessageDBEntity : NSObject 13 | 14 | 15 | @property(nonatomic,strong)NSString *sessionUri; 16 | @property(nonatomic,strong)NSString *sessionUserid; 17 | @property(nonatomic,assign)ChatSessionType sessionType; 18 | 19 | @property(nonatomic,strong)NSString *speakerName; 20 | @property(nonatomic,strong)NSString *speakerUri; 21 | @property(nonatomic,strong)NSString *speakerUserID; 22 | 23 | @property(nonatomic,assign)NSTimeInterval msgTime; 24 | @property(nonatomic,strong)NSString *msgId; 25 | @property(nonatomic,strong)NSString *msgContent; 26 | @property(nonatomic,strong)NSString *originalContent; 27 | @property(nonatomic,strong)NSString *supportLists; 28 | 29 | @property(nonatomic,assign)long long rqMsgId; 30 | @property(nonatomic,assign)BOOL isRead; 31 | @property(nonatomic,assign)MessageStatus status; 32 | @property(nonatomic,assign)BOOL isReceive; 33 | @property(nonatomic,assign)BOOL isResendMessage; 34 | @property(nonatomic,assign)BOOL isCC; 35 | @property(nonatomic,assign)CGFloat cellHeight; 36 | @property(nonatomic,assign)MessageType msgType; 37 | 38 | @property(nonatomic,strong)NSString *fontName; 39 | 40 | @property(nonatomic,assign)BOOL bSending; 41 | @property(nonatomic,assign)BOOL isSmsMsg; 42 | @property(nonatomic,assign)BOOL isCloudBackupMsg; 43 | 44 | @property(nonatomic,strong)NSString* rmsId; 45 | @property(nonatomic,assign)ThumbDownloadState dowloadState; 46 | @property (nonatomic, copy) NSString *contentType; 47 | 48 | 49 | @property (nonatomic, copy) NSString *strThumbLocalPath; 50 | 51 | 52 | @property (nonatomic, strong) NSString *fileName; 53 | @property (nonatomic, strong) NSString *emotionShutcut; 54 | @property (nonatomic, strong) NSString *emotionName; 55 | @property (nonatomic, strong) NSString *downloadUrl; 56 | 57 | @property(nonatomic,assign)EAVPromptType avPromptMsgType; 58 | 59 | 60 | @end 61 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/DataModel/GXMessageDBEntity.m: -------------------------------------------------------------------------------- 1 | // 2 | // FtChatMessageDBEntity.m 3 | // FetionHDLogic 4 | // 5 | // Created by Gerry on 14-5-30. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import "GXMessageDBEntity.h" 10 | 11 | 12 | @implementation GXMessageDBEntity 13 | 14 | 15 | - (void) dealloc { 16 | 17 | self.sessionUri = nil; 18 | self.sessionUserid = nil; 19 | self.speakerName = nil; 20 | self.speakerUri = nil; 21 | self.speakerUserID = nil; 22 | 23 | self.msgId = nil; 24 | self.msgContent = nil; 25 | self.originalContent = nil; 26 | self.supportLists = nil; 27 | 28 | self.fontName = nil; 29 | self.rmsId = nil; 30 | self.contentType = nil; 31 | 32 | 33 | self.fileName = nil; 34 | self.emotionShutcut = nil; 35 | self.emotionName = nil; 36 | self.downloadUrl = nil; 37 | } 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "scale" : "2x", 6 | "size" : "20x20" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "scale" : "3x", 11 | "size" : "20x20" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "scale" : "2x", 16 | "size" : "29x29" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "scale" : "3x", 21 | "size" : "29x29" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "scale" : "2x", 26 | "size" : "40x40" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "scale" : "3x", 31 | "size" : "40x40" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "scale" : "2x", 36 | "size" : "60x60" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "scale" : "3x", 41 | "size" : "60x60" 42 | }, 43 | { 44 | "idiom" : "ios-marketing", 45 | "scale" : "1x", 46 | "size" : "1024x1024" 47 | } 48 | ], 49 | "info" : { 50 | "author" : "xcode", 51 | "version" : 1 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "extent" : "full-screen", 5 | "filename" : "default_1.png", 6 | "idiom" : "iphone", 7 | "minimum-system-version" : "12.0", 8 | "orientation" : "portrait", 9 | "scale" : "3x", 10 | "subtype" : "2688h" 11 | }, 12 | { 13 | "extent" : "full-screen", 14 | "idiom" : "iphone", 15 | "minimum-system-version" : "12.0", 16 | "orientation" : "landscape", 17 | "scale" : "3x", 18 | "subtype" : "2688h" 19 | }, 20 | { 21 | "extent" : "full-screen", 22 | "filename" : "default_2.png", 23 | "idiom" : "iphone", 24 | "minimum-system-version" : "12.0", 25 | "orientation" : "portrait", 26 | "scale" : "2x", 27 | "subtype" : "1792h" 28 | }, 29 | { 30 | "extent" : "full-screen", 31 | "idiom" : "iphone", 32 | "minimum-system-version" : "12.0", 33 | "orientation" : "landscape", 34 | "scale" : "2x", 35 | "subtype" : "1792h" 36 | }, 37 | { 38 | "extent" : "full-screen", 39 | "filename" : "default_3.png", 40 | "idiom" : "iphone", 41 | "minimum-system-version" : "11.0", 42 | "orientation" : "portrait", 43 | "scale" : "3x", 44 | "subtype" : "2436h" 45 | }, 46 | { 47 | "extent" : "full-screen", 48 | "idiom" : "iphone", 49 | "minimum-system-version" : "11.0", 50 | "orientation" : "landscape", 51 | "scale" : "3x", 52 | "subtype" : "2436h" 53 | }, 54 | { 55 | "extent" : "full-screen", 56 | "filename" : "default_4.png", 57 | "idiom" : "iphone", 58 | "minimum-system-version" : "8.0", 59 | "orientation" : "portrait", 60 | "scale" : "3x", 61 | "subtype" : "736h" 62 | }, 63 | { 64 | "extent" : "full-screen", 65 | "idiom" : "iphone", 66 | "minimum-system-version" : "8.0", 67 | "orientation" : "landscape", 68 | "scale" : "3x", 69 | "subtype" : "736h" 70 | }, 71 | { 72 | "extent" : "full-screen", 73 | "filename" : "default_5.png", 74 | "idiom" : "iphone", 75 | "minimum-system-version" : "8.0", 76 | "orientation" : "portrait", 77 | "scale" : "2x", 78 | "subtype" : "667h" 79 | }, 80 | { 81 | "extent" : "full-screen", 82 | "idiom" : "iphone", 83 | "minimum-system-version" : "7.0", 84 | "orientation" : "portrait", 85 | "scale" : "2x" 86 | }, 87 | { 88 | "extent" : "full-screen", 89 | "idiom" : "iphone", 90 | "minimum-system-version" : "7.0", 91 | "orientation" : "portrait", 92 | "scale" : "2x", 93 | "subtype" : "retina4" 94 | }, 95 | { 96 | "extent" : "full-screen", 97 | "idiom" : "iphone", 98 | "orientation" : "portrait", 99 | "scale" : "1x" 100 | }, 101 | { 102 | "extent" : "full-screen", 103 | "idiom" : "iphone", 104 | "orientation" : "portrait", 105 | "scale" : "2x" 106 | }, 107 | { 108 | "extent" : "full-screen", 109 | "idiom" : "iphone", 110 | "orientation" : "portrait", 111 | "scale" : "2x", 112 | "subtype" : "retina4" 113 | } 114 | ], 115 | "info" : { 116 | "author" : "xcode", 117 | "version" : 1 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_1.png -------------------------------------------------------------------------------- /DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_2.png -------------------------------------------------------------------------------- /DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_3.png -------------------------------------------------------------------------------- /DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_4.png -------------------------------------------------------------------------------- /DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/Images.xcassets/LaunchImage.launchimage/default_5.png -------------------------------------------------------------------------------- /DBDemo/DBDemo/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | iDream.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UIRequiredDeviceCapabilities 26 | 27 | armv7 28 | 29 | UISupportedInterfaceOrientations 30 | 31 | UIInterfaceOrientationPortrait 32 | UIInterfaceOrientationLandscapeLeft 33 | UIInterfaceOrientationLandscapeRight 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import "FMDatabase.h" 11 | #import "GXMessage.h" 12 | #import "GXDatabaseManager.h" 13 | #import "NSObject+serializable.h" 14 | #import "GXMessageDBEntity.h" 15 | #import "GXSQLStatementManager.h" 16 | 17 | @interface ViewController () 18 | 19 | @property (nonatomic, strong) UITextView *textView; 20 | @property (nonatomic, strong) GXMessage *testMessage; 21 | 22 | @property (nonatomic, retain) FMDatabase *database; // used to load test data 加载测试数据用 23 | @property (nonatomic, retain) FMDatabase *testDatabase; // CRUD 24 | @end 25 | 26 | @implementation ViewController 27 | 28 | - (void)viewDidLoad { 29 | [super viewDidLoad]; 30 | // Do any additional setup after loading the view, typically from a nib. 31 | 32 | self.view.backgroundColor = [UIColor whiteColor]; 33 | [self addView]; 34 | } 35 | 36 | - (void)didReceiveMemoryWarning { 37 | [super didReceiveMemoryWarning]; 38 | // Dispose of any resources that can be recreated. 39 | } 40 | 41 | 42 | - (void)addView { 43 | 44 | CGRect bounds = [[UIScreen mainScreen] bounds]; 45 | 46 | self.textView = [[UITextView alloc] initWithFrame:CGRectMake(5, 40, CGRectGetWidth(bounds)-10, 200)]; 47 | self.textView.layer.borderColor = [UIColor orangeColor].CGColor; 48 | self.textView.layer.borderWidth = 1; 49 | self.textView.layer.cornerRadius = 4; 50 | self.textView.editable = NO; 51 | [self.view addSubview:self.textView]; 52 | 53 | CGFloat gap = 10; 54 | 55 | CGFloat posX = 10; 56 | CGFloat posY = 250; 57 | CGFloat width = (CGRectGetWidth(bounds)-30)/2; 58 | CGFloat height = 40; 59 | 60 | // 1 61 | CGRect frame = CGRectMake(posX, posY, width, height); 62 | UIButton *loadTestDataBtn = [self buttonWithFrame:frame withTitle:@"读取测试数据" withSelector:@selector(loadTestDataBtnPressed:)]; 63 | [self.view addSubview:loadTestDataBtn]; 64 | 65 | // 2 66 | posX += width + gap; 67 | frame.origin.x = posX; 68 | UIButton *insertTestDataBtn = [self buttonWithFrame:frame withTitle:@"创建表并插入测试数据" withSelector:@selector(insertTestDataBtnPressed:)]; 69 | [self.view addSubview:insertTestDataBtn]; 70 | 71 | // 3 72 | width = (CGRectGetWidth(bounds)-40)/3; 73 | posX = gap; 74 | posY += height + gap; 75 | frame.origin.x = posX; 76 | frame.origin.y = posY; 77 | frame.size.width = width; 78 | UIButton *selectDataBtn = [self buttonWithFrame:frame withTitle:@"查询数据" withSelector:@selector(selectDataBtnPressed:)]; 79 | [self.view addSubview:selectDataBtn]; 80 | 81 | // 4 82 | posX += width + gap; 83 | frame.origin.x = posX; 84 | UIButton *updateDataBtn = [self buttonWithFrame:frame withTitle:@"更新数据" withSelector:@selector(updateDataBtnPressed:)]; 85 | [self.view addSubview:updateDataBtn]; 86 | 87 | // 5 88 | posX += width + gap; 89 | frame.origin.x = posX; 90 | UIButton *deleteDataBtn = [self buttonWithFrame:frame withTitle:@"删除数据" withSelector:@selector(deleteDataBtnPressed:)]; 91 | [self.view addSubview:deleteDataBtn]; 92 | } 93 | 94 | - (UIButton *)buttonWithFrame:(CGRect)frame withTitle:(NSString *)title withSelector:(SEL)selector { 95 | UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 96 | button.frame = frame; 97 | button.titleLabel.font = [UIFont systemFontOfSize:13]; 98 | button.backgroundColor = [UIColor purpleColor]; 99 | button.layer.masksToBounds = YES; 100 | button.layer.cornerRadius = 4; 101 | [button setTitle:title forState:UIControlStateNormal]; 102 | [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside]; 103 | 104 | return button; 105 | } 106 | 107 | #pragma mark - UIButton event 108 | -(void)loadTestDataBtnPressed:(id)sender { 109 | [self loadTestDataFromTestDB]; 110 | } 111 | 112 | -(void)insertTestDataBtnPressed:(id)sender { 113 | if (self.testMessage) { 114 | [self testReplaceIntoSQL:self.testMessage]; 115 | } else { 116 | NSLog(@"未加载测试数据"); 117 | } 118 | } 119 | 120 | -(void)selectDataBtnPressed:(id)sender { 121 | [self testSelectSQL]; 122 | } 123 | 124 | -(void)updateDataBtnPressed:(id)sender { 125 | [self testUpdateSQL]; 126 | } 127 | 128 | -(void)deleteDataBtnPressed:(id)sender { 129 | [self testDeleteSQL]; 130 | } 131 | 132 | #pragma mark - load test data 133 | - (void)loadTestDataFromTestDB { 134 | 135 | NSMutableArray *arr = [NSMutableArray arrayWithCapacity:10]; 136 | 137 | FMResultSet *rs = [self.database executeQuery:@"select * from t_message_chat"]; 138 | 139 | while ([rs next]) { 140 | 141 | GXMessage *msg = [[GXMessage alloc] init]; 142 | 143 | msg.sessionUri = [rs stringForColumn:@"_sessionUri"]; 144 | msg.sessionUserid = [rs stringForColumn:@"_sessionUserid"]; 145 | msg.speakerName = [rs stringForColumn:@"_speakerName"]; 146 | msg.speakerUri = [rs stringForColumn:@"_speakerUri"]; 147 | msg.speakerUserID = [rs stringForColumn:@"_speakerUserID"]; 148 | msg.msgId = [rs stringForColumn:@"_msgId"]; 149 | msg.msgContent = [rs stringForColumn:@"_msgContent"]; 150 | msg.originalContent = [rs stringForColumn:@"_originalContent"]; 151 | msg.supportLists = [rs stringForColumn:@"_supportLists"]; 152 | msg.rmsId = [rs stringForColumn:@"_rmsId"]; 153 | 154 | msg.rqMsgId = [rs longLongIntForColumn:@"_rqMsgId"]; 155 | msg.msgTime = [rs doubleForColumn:@"_msgTime"]; 156 | 157 | msg.sessionType = [rs intForColumn:@"_sessionType"]; 158 | msg.status = [rs intForColumn:@"_status"]; 159 | msg.avPromptMsgType = [rs intForColumn:@"_avPromptMsgType"]; 160 | 161 | msg.isReceive = [rs boolForColumn:@"_isReceive"]; 162 | msg.isCC = [rs boolForColumn:@"_isCC"]; 163 | msg.bSending = [rs boolForColumn:@"_bSending"]; 164 | msg.isSmsMsg = [rs boolForColumn:@"_isSmsMsg"]; 165 | msg.isCloudBackupMsg = [rs boolForColumn:@"_isCloudBackupMsg"]; 166 | 167 | [arr addObject:msg]; 168 | } 169 | 170 | if (arr.count > 6) { 171 | self.testMessage = arr[6]; 172 | self.textView.text = @"加载测试数据成功"; 173 | } 174 | else { 175 | NSLog(@"load test data failure."); 176 | self.textView.text = @"加载测试数据失败"; 177 | } 178 | } 179 | 180 | #pragma mark - db 181 | - (FMDatabase *)database { 182 | if (!_database) { 183 | NSString *databasePath = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite"]; 184 | _database = [FMDatabase databaseWithPath:databasePath]; 185 | } 186 | 187 | if (![_database open]) { 188 | NSLog(@"open database failure."); 189 | self.textView.text = @"打开本地测试数据库失败"; 190 | return nil; 191 | } 192 | return _database; 193 | } 194 | 195 | - (NSString *)stringWithRes:(BOOL)res { 196 | return (res ? @"成功" : @"失败"); 197 | } 198 | 199 | #pragma mark - Use GXDatabaseUtils 200 | - (void)testReplaceIntoSQL:(GXMessage *)msg { 201 | 202 | NSString *dbPath = [NSHomeDirectory() stringByAppendingPathComponent:@"testDB.sqlite"]; 203 | BOOL res = [GXDatabaseManager databaseWithPath:dbPath]; 204 | 205 | // create table 206 | res = [GXDatabaseManager createTable:@"t_message" withClass:[GXMessage class] withPrimaryKey:@"_msgId"]; 207 | 208 | // test sql 209 | NSString *createSQL = [GXSQLStatementManager create:@"t_message" 210 | withClass:[GXMessage class] 211 | withPrimaryKey:@"_msgId"]; 212 | self.textView.text = [NSString stringWithFormat:@"%@,表创建%@", createSQL, [self stringWithRes:res]]; 213 | 214 | // replace into 215 | [GXDatabaseManager replaceInto:@"t_message" withObject:msg]; 216 | } 217 | 218 | - (void) testSelectSQL { 219 | 220 | NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite"]; 221 | BOOL res = [GXDatabaseManager databaseWithPath:dbPath]; 222 | if (!res) { 223 | NSLog(@"ERROR..."); 224 | } 225 | 226 | NSString *w1 = kWhereString(@"_sessionUserid", @"="); 227 | NSString *w2 = kWhereString(@"_msgId", @"="); 228 | NSString *w = kWhereCombination(w1, @"AND", w2); 229 | 230 | // select * from table 231 | NSArray*arr= [GXDatabaseManager selectObjects:[GXMessageDBEntity class] 232 | fromTable:@"t_message_chat" 233 | where:w 234 | withParams:@[@"1525851662", @"0b178efa-eb51-4e14-a863-78afd8b9d5ad"] 235 | orderBy:@"_msgTime" 236 | withSortType:@"DESC" 237 | withRange:NSMakeRange(0, 5)]; 238 | // test sql 239 | NSString *selectSQL = [GXSQLStatementManager select:@"t_message_chat" 240 | where:w 241 | orderBy:@"_msgTime" 242 | sortType:@"DESC" 243 | limit:NSMakeRange(0, 5)]; 244 | self.textView.text = [NSString stringWithFormat:@"%@,数据:%@", selectSQL, arr]; 245 | } 246 | 247 | - (void)testUpdateSQL { 248 | 249 | NSString *dbPath = [NSHomeDirectory() stringByAppendingPathComponent:@"testDB.sqlite"]; 250 | BOOL res = [GXDatabaseManager databaseWithPath:dbPath]; 251 | 252 | if (!res) NSLog(@"ERROR"); 253 | 254 | // update table 255 | NSString *w = kWhereString(@"_msgId", @"="); 256 | res = [GXDatabaseManager updateTable:@"t_message" 257 | set:@[@"_fontName"] 258 | where:w 259 | withParams:@[@"Arial", @"0b178efa-eb51-4e14-a863-78afd8b9d5ad"]]; 260 | 261 | // test sql 262 | NSString *updateSQL = [GXSQLStatementManager update:@"t_message" 263 | set:@[@"_fontName"] where:w]; 264 | self.textView.text = [NSString stringWithFormat:@"%@,更新数据:%@", updateSQL, [self stringWithRes:res]]; 265 | } 266 | 267 | - (void)testDeleteSQL { 268 | 269 | NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite"]; 270 | BOOL res = [GXDatabaseManager databaseWithPath:dbPath]; 271 | if (!res) NSLog(@"ERROR..."); 272 | 273 | // delete talbe 274 | res = [GXDatabaseManager deleteTable:@"t_message_chat" 275 | where:@"_msgId=?" 276 | withParams:@[@"0b178efa-eb51-4e14-a863-78afd8b9d5ad"]]; 277 | 278 | // test sql 279 | NSString *deleteSQL = [GXSQLStatementManager delete:@"t_message_chat" 280 | where:@"_msgId=?" ]; 281 | self.textView.text = [NSString stringWithFormat:@"%@,删除数据:%@", deleteSQL, [self stringWithRes:res]]; 282 | 283 | // select count 284 | // [GXDatabaseManager selectCount:@"t_message_chat" where:@"_sessionUserid=?" withParams:@[@"1472516850"]]; 285 | } 286 | 287 | @end 288 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMDB.h: -------------------------------------------------------------------------------- 1 | #import "FMDatabase.h" 2 | #import "FMResultSet.h" 3 | #import "FMDatabaseAdditions.h" 4 | #import "FMDatabaseQueue.h" 5 | #import "FMDatabasePool.h" 6 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMDatabase.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "sqlite3.h" 3 | #import "FMResultSet.h" 4 | #import "FMDatabasePool.h" 5 | 6 | 7 | #if ! __has_feature(objc_arc) 8 | #define FMDBAutorelease(__v) ([__v autorelease]); 9 | #define FMDBReturnAutoreleased FMDBAutorelease 10 | 11 | #define FMDBRetain(__v) ([__v retain]); 12 | #define FMDBReturnRetained FMDBRetain 13 | 14 | #define FMDBRelease(__v) ([__v release]); 15 | 16 | #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); 17 | #else 18 | // -fobjc-arc 19 | #define FMDBAutorelease(__v) 20 | #define FMDBReturnAutoreleased(__v) (__v) 21 | 22 | #define FMDBRetain(__v) 23 | #define FMDBReturnRetained(__v) (__v) 24 | 25 | #define FMDBRelease(__v) 26 | 27 | // If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects 28 | // and will participate in ARC. 29 | // See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. 30 | #if OS_OBJECT_USE_OBJC 31 | #define FMDBDispatchQueueRelease(__v) 32 | #else 33 | #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); 34 | #endif 35 | #endif 36 | 37 | #if !__has_feature(objc_instancetype) 38 | #define instancetype id 39 | #endif 40 | 41 | 42 | typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); 43 | 44 | 45 | /** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper. 46 | 47 | ### Usage 48 | The three main classes in FMDB are: 49 | 50 | - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. 51 | - `` - Represents the results of executing a query on an `FMDatabase`. 52 | - `` - If you want to perform queries and updates on multiple threads, you'll want to use this class. 53 | 54 | ### See also 55 | 56 | - `` - A pool of `FMDatabase` objects. 57 | - `` - A wrapper for `sqlite_stmt`. 58 | 59 | ### External links 60 | 61 | - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation 62 | - [SQLite web site](http://sqlite.org/) 63 | - [FMDB mailing list](http://groups.google.com/group/fmdb) 64 | - [SQLite FAQ](http://www.sqlite.org/faq.html) 65 | 66 | @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use ``. 67 | 68 | */ 69 | 70 | @interface FMDatabase : NSObject { 71 | 72 | sqlite3* _db; 73 | NSString* _databasePath; 74 | BOOL _logsErrors; 75 | BOOL _crashOnErrors; 76 | BOOL _traceExecution; 77 | BOOL _checkedOut; 78 | BOOL _shouldCacheStatements; 79 | BOOL _isExecutingStatement; 80 | BOOL _inTransaction; 81 | NSTimeInterval _maxBusyRetryTimeInterval; 82 | NSTimeInterval _startBusyRetryTime; 83 | 84 | NSMutableDictionary *_cachedStatements; 85 | NSMutableSet *_openResultSets; 86 | NSMutableSet *_openFunctions; 87 | 88 | NSDateFormatter *_dateFormat; 89 | } 90 | 91 | ///----------------- 92 | /// @name Properties 93 | ///----------------- 94 | 95 | /** Whether should trace execution */ 96 | 97 | @property (atomic, assign) BOOL traceExecution; 98 | 99 | /** Whether checked out or not */ 100 | 101 | @property (atomic, assign) BOOL checkedOut; 102 | 103 | /** Crash on errors */ 104 | 105 | @property (atomic, assign) BOOL crashOnErrors; 106 | 107 | /** Logs errors */ 108 | 109 | @property (atomic, assign) BOOL logsErrors; 110 | 111 | /** Dictionary of cached statements */ 112 | 113 | @property (atomic, retain) NSMutableDictionary *cachedStatements; 114 | 115 | ///--------------------- 116 | /// @name Initialization 117 | ///--------------------- 118 | 119 | /** Create a `FMDatabase` object. 120 | 121 | An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: 122 | 123 | 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 124 | 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. 125 | 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. 126 | 127 | For example, to create/open a database in your Mac OS X `tmp` folder: 128 | 129 | FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; 130 | 131 | Or, in iOS, you might open a database in the app's `Documents` directory: 132 | 133 | NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 134 | NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; 135 | FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; 136 | 137 | (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) 138 | 139 | @param inPath Path of database file 140 | 141 | @return `FMDatabase` object if successful; `nil` if failure. 142 | 143 | */ 144 | 145 | + (instancetype)databaseWithPath:(NSString*)inPath; 146 | 147 | /** Initialize a `FMDatabase` object. 148 | 149 | An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: 150 | 151 | 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 152 | 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. 153 | 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. 154 | 155 | For example, to create/open a database in your Mac OS X `tmp` folder: 156 | 157 | FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; 158 | 159 | Or, in iOS, you might open a database in the app's `Documents` directory: 160 | 161 | NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 162 | NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; 163 | FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; 164 | 165 | (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) 166 | 167 | @param inPath Path of database file 168 | 169 | @return `FMDatabase` object if successful; `nil` if failure. 170 | 171 | */ 172 | 173 | - (instancetype)initWithPath:(NSString*)inPath; 174 | 175 | 176 | ///----------------------------------- 177 | /// @name Opening and closing database 178 | ///----------------------------------- 179 | 180 | /** Opening a new database connection 181 | 182 | The database is opened for reading and writing, and is created if it does not already exist. 183 | 184 | @return `YES` if successful, `NO` on error. 185 | 186 | @see [sqlite3_open()](http://sqlite.org/c3ref/open.html) 187 | @see openWithFlags: 188 | @see close 189 | */ 190 | 191 | - (BOOL)open; 192 | 193 | /** Opening a new database connection with flags 194 | 195 | @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: 196 | 197 | `SQLITE_OPEN_READONLY` 198 | 199 | The database is opened in read-only mode. If the database does not already exist, an error is returned. 200 | 201 | `SQLITE_OPEN_READWRITE` 202 | 203 | The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. 204 | 205 | `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` 206 | 207 | The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. 208 | 209 | @return `YES` if successful, `NO` on error. 210 | 211 | @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) 212 | @see open 213 | @see close 214 | */ 215 | 216 | #if SQLITE_VERSION_NUMBER >= 3005000 217 | - (BOOL)openWithFlags:(int)flags; 218 | #endif 219 | 220 | /** Closing a database connection 221 | 222 | @return `YES` if success, `NO` on error. 223 | 224 | @see [sqlite3_close()](http://sqlite.org/c3ref/close.html) 225 | @see open 226 | @see openWithFlags: 227 | */ 228 | 229 | - (BOOL)close; 230 | 231 | /** Test to see if we have a good connection to the database. 232 | 233 | This will confirm whether: 234 | 235 | - is database open 236 | - if open, it will try a simple SELECT statement and confirm that it succeeds. 237 | 238 | @return `YES` if everything succeeds, `NO` on failure. 239 | */ 240 | 241 | - (BOOL)goodConnection; 242 | 243 | 244 | ///---------------------- 245 | /// @name Perform updates 246 | ///---------------------- 247 | 248 | /** Execute single update statement 249 | 250 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. 251 | 252 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 253 | 254 | @param sql The SQL to be performed, with optional `?` placeholders. 255 | 256 | @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned. 257 | 258 | @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). 259 | 260 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 261 | 262 | @see lastError 263 | @see lastErrorCode 264 | @see lastErrorMessage 265 | @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) 266 | */ 267 | 268 | - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...; 269 | 270 | /** Execute single update statement 271 | 272 | @see executeUpdate:withErrorAndBindings: 273 | 274 | @warning **Deprecated**: Please use `` instead. 275 | */ 276 | 277 | - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated)); 278 | 279 | /** Execute single update statement 280 | 281 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. 282 | 283 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 284 | 285 | @param sql The SQL to be performed, with optional `?` placeholders. 286 | 287 | @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). 288 | 289 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 290 | 291 | @see lastError 292 | @see lastErrorCode 293 | @see lastErrorMessage 294 | @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) 295 | 296 | @note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. 297 | */ 298 | 299 | - (BOOL)executeUpdate:(NSString*)sql, ...; 300 | 301 | /** Execute single update statement 302 | 303 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method. 304 | 305 | @param format The SQL to be performed, with `printf`-style escape sequences. 306 | 307 | @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. 308 | 309 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 310 | 311 | @see executeUpdate: 312 | @see lastError 313 | @see lastErrorCode 314 | @see lastErrorMessage 315 | 316 | @warning This should be used with great care. Generally, instead of this method, you should use `` (with `?` placeholders in the SQL), which properly escapes quotation marks encountered inside the values (minimizing errors and protecting against SQL injection attack) and handles a wider variety of data types. See `` for more information. 317 | */ 318 | 319 | - (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); 320 | 321 | /** Execute single update statement 322 | 323 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. 324 | 325 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 326 | 327 | @param sql The SQL to be performed, with optional `?` placeholders. 328 | 329 | @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. 330 | 331 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 332 | 333 | @see lastError 334 | @see lastErrorCode 335 | @see lastErrorMessage 336 | */ 337 | 338 | - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; 339 | 340 | /** Execute single update statement 341 | 342 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. 343 | 344 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 345 | 346 | @param sql The SQL to be performed, with optional `?` placeholders. 347 | 348 | @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. 349 | 350 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 351 | 352 | @see lastError 353 | @see lastErrorCode 354 | @see lastErrorMessage 355 | */ 356 | 357 | - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments; 358 | 359 | 360 | /** Execute single update statement 361 | 362 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. 363 | 364 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 365 | 366 | @param sql The SQL to be performed, with optional `?` placeholders. 367 | 368 | @param args A `va_list` of arguments. 369 | 370 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 371 | 372 | @see lastError 373 | @see lastErrorCode 374 | @see lastErrorMessage 375 | */ 376 | 377 | - (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args; 378 | 379 | /** Execute multiple SQL statements 380 | 381 | This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. 382 | 383 | @param sql The SQL to be performed 384 | 385 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 386 | 387 | @see executeStatements:withResultBlock: 388 | @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) 389 | 390 | */ 391 | 392 | - (BOOL)executeStatements:(NSString *)sql; 393 | 394 | /** Execute multiple SQL statements with callback handler 395 | 396 | This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. 397 | 398 | @param sql The SQL to be performed. 399 | @param block A block that will be called for any result sets returned by any SQL statements. 400 | Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK), 401 | non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary. 402 | This may be `nil` if you don't care to receive any results. 403 | 404 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, 405 | ``, or `` for diagnostic information regarding the failure. 406 | 407 | @see executeStatements: 408 | @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) 409 | 410 | */ 411 | 412 | - (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block; 413 | 414 | /** Last insert rowid 415 | 416 | Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid. 417 | 418 | This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned. 419 | 420 | @return The rowid of the last inserted row. 421 | 422 | @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html) 423 | 424 | */ 425 | 426 | - (sqlite_int64)lastInsertRowId; 427 | 428 | /** The number of rows changed by prior SQL statement. 429 | 430 | This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted. 431 | 432 | @return The number of rows changed by prior SQL statement. 433 | 434 | @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html) 435 | 436 | */ 437 | 438 | - (int)changes; 439 | 440 | 441 | ///------------------------- 442 | /// @name Retrieving results 443 | ///------------------------- 444 | 445 | /** Execute select statement 446 | 447 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 448 | 449 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 450 | 451 | This method employs [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method. 452 | 453 | @param sql The SELECT statement to be performed, with optional `?` placeholders. 454 | 455 | @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). 456 | 457 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 458 | 459 | @see FMResultSet 460 | @see [`FMResultSet next`](<[FMResultSet next]>) 461 | @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) 462 | */ 463 | 464 | - (FMResultSet *)executeQuery:(NSString*)sql, ...; 465 | 466 | /** Execute select statement 467 | 468 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 469 | 470 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 471 | 472 | @param format The SQL to be performed, with `printf`-style escape sequences. 473 | 474 | @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. 475 | 476 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 477 | 478 | @see executeQuery: 479 | @see FMResultSet 480 | @see [`FMResultSet next`](<[FMResultSet next]>) 481 | 482 | @warning This should be used with great care. Generally, instead of this method, you should use `` (with `?` placeholders in the SQL), which properly escapes quotation marks encountered inside the values (minimizing errors and protecting against SQL injection attack) and handles a wider variety of data types. See `` for more information. 483 | 484 | */ 485 | 486 | - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); 487 | 488 | /** Execute select statement 489 | 490 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 491 | 492 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 493 | 494 | @param sql The SELECT statement to be performed, with optional `?` placeholders. 495 | 496 | @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. 497 | 498 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 499 | 500 | @see FMResultSet 501 | @see [`FMResultSet next`](<[FMResultSet next]>) 502 | */ 503 | 504 | - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; 505 | 506 | /** Execute select statement 507 | 508 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 509 | 510 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 511 | 512 | @param sql The SELECT statement to be performed, with optional `?` placeholders. 513 | 514 | @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. 515 | 516 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 517 | 518 | @see FMResultSet 519 | @see [`FMResultSet next`](<[FMResultSet next]>) 520 | */ 521 | 522 | - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments; 523 | 524 | 525 | // Documentation forthcoming. 526 | - (FMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args; 527 | 528 | ///------------------- 529 | /// @name Transactions 530 | ///------------------- 531 | 532 | /** Begin a transaction 533 | 534 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 535 | 536 | @see commit 537 | @see rollback 538 | @see beginDeferredTransaction 539 | @see inTransaction 540 | */ 541 | 542 | - (BOOL)beginTransaction; 543 | 544 | /** Begin a deferred transaction 545 | 546 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 547 | 548 | @see commit 549 | @see rollback 550 | @see beginTransaction 551 | @see inTransaction 552 | */ 553 | 554 | - (BOOL)beginDeferredTransaction; 555 | 556 | /** Commit a transaction 557 | 558 | Commit a transaction that was initiated with either `` or with ``. 559 | 560 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 561 | 562 | @see beginTransaction 563 | @see beginDeferredTransaction 564 | @see rollback 565 | @see inTransaction 566 | */ 567 | 568 | - (BOOL)commit; 569 | 570 | /** Rollback a transaction 571 | 572 | Rollback a transaction that was initiated with either `` or with ``. 573 | 574 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 575 | 576 | @see beginTransaction 577 | @see beginDeferredTransaction 578 | @see commit 579 | @see inTransaction 580 | */ 581 | 582 | - (BOOL)rollback; 583 | 584 | /** Identify whether currently in a transaction or not 585 | 586 | @return `YES` if currently within transaction; `NO` if not. 587 | 588 | @see beginTransaction 589 | @see beginDeferredTransaction 590 | @see commit 591 | @see rollback 592 | */ 593 | 594 | - (BOOL)inTransaction; 595 | 596 | 597 | ///---------------------------------------- 598 | /// @name Cached statements and result sets 599 | ///---------------------------------------- 600 | 601 | /** Clear cached statements */ 602 | 603 | - (void)clearCachedStatements; 604 | 605 | /** Close all open result sets */ 606 | 607 | - (void)closeOpenResultSets; 608 | 609 | /** Whether database has any open result sets 610 | 611 | @return `YES` if there are open result sets; `NO` if not. 612 | */ 613 | 614 | - (BOOL)hasOpenResultSets; 615 | 616 | /** Return whether should cache statements or not 617 | 618 | @return `YES` if should cache statements; `NO` if not. 619 | */ 620 | 621 | - (BOOL)shouldCacheStatements; 622 | 623 | /** Set whether should cache statements or not 624 | 625 | @param value `YES` if should cache statements; `NO` if not. 626 | */ 627 | 628 | - (void)setShouldCacheStatements:(BOOL)value; 629 | 630 | 631 | ///------------------------- 632 | /// @name Encryption methods 633 | ///------------------------- 634 | 635 | /** Set encryption key. 636 | 637 | @param key The key to be used. 638 | 639 | @return `YES` if success, `NO` on error. 640 | 641 | @see http://www.sqlite-encrypt.com/develop-guide.htm 642 | 643 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 644 | */ 645 | 646 | - (BOOL)setKey:(NSString*)key; 647 | 648 | /** Reset encryption key 649 | 650 | @param key The key to be used. 651 | 652 | @return `YES` if success, `NO` on error. 653 | 654 | @see http://www.sqlite-encrypt.com/develop-guide.htm 655 | 656 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 657 | */ 658 | 659 | - (BOOL)rekey:(NSString*)key; 660 | 661 | /** Set encryption key using `keyData`. 662 | 663 | @param keyData The `NSData` to be used. 664 | 665 | @return `YES` if success, `NO` on error. 666 | 667 | @see http://www.sqlite-encrypt.com/develop-guide.htm 668 | 669 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 670 | */ 671 | 672 | - (BOOL)setKeyWithData:(NSData *)keyData; 673 | 674 | /** Reset encryption key using `keyData`. 675 | 676 | @param keyData The `NSData` to be used. 677 | 678 | @return `YES` if success, `NO` on error. 679 | 680 | @see http://www.sqlite-encrypt.com/develop-guide.htm 681 | 682 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 683 | */ 684 | 685 | - (BOOL)rekeyWithData:(NSData *)keyData; 686 | 687 | 688 | ///------------------------------ 689 | /// @name General inquiry methods 690 | ///------------------------------ 691 | 692 | /** The path of the database file 693 | 694 | @return path of database. 695 | 696 | */ 697 | 698 | - (NSString *)databasePath; 699 | 700 | /** The underlying SQLite handle 701 | 702 | @return The `sqlite3` pointer. 703 | 704 | */ 705 | 706 | - (sqlite3*)sqliteHandle; 707 | 708 | 709 | ///----------------------------- 710 | /// @name Retrieving error codes 711 | ///----------------------------- 712 | 713 | /** Last error message 714 | 715 | Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. 716 | 717 | @return `NSString` of the last error message. 718 | 719 | @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html) 720 | @see lastErrorCode 721 | @see lastError 722 | 723 | */ 724 | 725 | - (NSString*)lastErrorMessage; 726 | 727 | /** Last error code 728 | 729 | Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. 730 | 731 | @return Integer value of the last error code. 732 | 733 | @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html) 734 | @see lastErrorMessage 735 | @see lastError 736 | 737 | */ 738 | 739 | - (int)lastErrorCode; 740 | 741 | /** Had error 742 | 743 | @return `YES` if there was an error, `NO` if no error. 744 | 745 | @see lastError 746 | @see lastErrorCode 747 | @see lastErrorMessage 748 | 749 | */ 750 | 751 | - (BOOL)hadError; 752 | 753 | /** Last error 754 | 755 | @return `NSError` representing the last error. 756 | 757 | @see lastErrorCode 758 | @see lastErrorMessage 759 | 760 | */ 761 | 762 | - (NSError*)lastError; 763 | 764 | 765 | // description forthcoming 766 | - (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds; 767 | - (NSTimeInterval)maxBusyRetryTimeInterval; 768 | 769 | 770 | #if SQLITE_VERSION_NUMBER >= 3007000 771 | 772 | ///------------------ 773 | /// @name Save points 774 | ///------------------ 775 | 776 | /** Start save point 777 | 778 | @param name Name of save point. 779 | 780 | @param outErr A `NSError` object to receive any error object (if any). 781 | 782 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 783 | 784 | @see releaseSavePointWithName:error: 785 | @see rollbackToSavePointWithName:error: 786 | */ 787 | 788 | - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr; 789 | 790 | /** Release save point 791 | 792 | @param name Name of save point. 793 | 794 | @param outErr A `NSError` object to receive any error object (if any). 795 | 796 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 797 | 798 | @see startSavePointWithName:error: 799 | @see rollbackToSavePointWithName:error: 800 | 801 | */ 802 | 803 | - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr; 804 | 805 | /** Roll back to save point 806 | 807 | @param name Name of save point. 808 | @param outErr A `NSError` object to receive any error object (if any). 809 | 810 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 811 | 812 | @see startSavePointWithName:error: 813 | @see releaseSavePointWithName:error: 814 | 815 | */ 816 | 817 | - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr; 818 | 819 | /** Start save point 820 | 821 | @param block Block of code to perform from within save point. 822 | 823 | @return The NSError corresponding to the error, if any. If no error, returns `nil`. 824 | 825 | @see startSavePointWithName:error: 826 | @see releaseSavePointWithName:error: 827 | @see rollbackToSavePointWithName:error: 828 | 829 | */ 830 | 831 | - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block; 832 | 833 | #endif 834 | 835 | ///---------------------------- 836 | /// @name SQLite library status 837 | ///---------------------------- 838 | 839 | /** Test to see if the library is threadsafe 840 | 841 | @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0. 842 | 843 | @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html) 844 | */ 845 | 846 | + (BOOL)isSQLiteThreadSafe; 847 | 848 | /** Run-time library version numbers 849 | 850 | @return The sqlite library version string. 851 | 852 | @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html) 853 | */ 854 | 855 | + (NSString*)sqliteLibVersion; 856 | 857 | 858 | + (NSString*)FMDBUserVersion; 859 | 860 | + (SInt32)FMDBVersion; 861 | 862 | 863 | ///------------------------ 864 | /// @name Make SQL function 865 | ///------------------------ 866 | 867 | /** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. 868 | 869 | For example: 870 | 871 | [queue inDatabase:^(FMDatabase *adb) { 872 | 873 | [adb executeUpdate:@"create table ftest (foo text)"]; 874 | [adb executeUpdate:@"insert into ftest values ('hello')"]; 875 | [adb executeUpdate:@"insert into ftest values ('hi')"]; 876 | [adb executeUpdate:@"insert into ftest values ('not h!')"]; 877 | [adb executeUpdate:@"insert into ftest values ('definitely not h!')"]; 878 | 879 | [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) { 880 | if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) { 881 | @autoreleasepool { 882 | const char *c = (const char *)sqlite3_value_text(aargv[0]); 883 | NSString *s = [NSString stringWithUTF8String:c]; 884 | sqlite3_result_int(context, [s hasPrefix:@"h"]); 885 | } 886 | } 887 | else { 888 | NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__); 889 | sqlite3_result_null(context); 890 | } 891 | }]; 892 | 893 | int rowCount = 0; 894 | FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"]; 895 | while ([ars next]) { 896 | rowCount++; 897 | NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]); 898 | } 899 | FMDBQuickCheck(rowCount == 2); 900 | }]; 901 | 902 | @param name Name of function 903 | 904 | @param count Maximum number of parameters 905 | 906 | @param block The block of code for the function 907 | 908 | @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html) 909 | */ 910 | 911 | - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block; 912 | 913 | 914 | ///--------------------- 915 | /// @name Date formatter 916 | ///--------------------- 917 | 918 | /** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales. 919 | 920 | Use this method to generate values to set the dateFormat property. 921 | 922 | Example: 923 | 924 | myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 925 | 926 | @param format A valid NSDateFormatter format string. 927 | 928 | @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa. 929 | 930 | @see hasDateFormatter 931 | @see setDateFormat: 932 | @see dateFromString: 933 | @see stringFromDate: 934 | @see storeableDateFormat: 935 | 936 | @warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes. 937 | 938 | */ 939 | 940 | + (NSDateFormatter *)storeableDateFormat:(NSString *)format; 941 | 942 | /** Test whether the database has a date formatter assigned. 943 | 944 | @return `YES` if there is a date formatter; `NO` if not. 945 | 946 | @see hasDateFormatter 947 | @see setDateFormat: 948 | @see dateFromString: 949 | @see stringFromDate: 950 | @see storeableDateFormat: 951 | */ 952 | 953 | - (BOOL)hasDateFormatter; 954 | 955 | /** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps. 956 | 957 | @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat. 958 | 959 | @see hasDateFormatter 960 | @see setDateFormat: 961 | @see dateFromString: 962 | @see stringFromDate: 963 | @see storeableDateFormat: 964 | 965 | @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe. 966 | */ 967 | 968 | - (void)setDateFormat:(NSDateFormatter *)format; 969 | 970 | /** Convert the supplied NSString to NSDate, using the current database formatter. 971 | 972 | @param s `NSString` to convert to `NSDate`. 973 | 974 | @return The `NSDate` object; or `nil` if no formatter is set. 975 | 976 | @see hasDateFormatter 977 | @see setDateFormat: 978 | @see dateFromString: 979 | @see stringFromDate: 980 | @see storeableDateFormat: 981 | */ 982 | 983 | - (NSDate *)dateFromString:(NSString *)s; 984 | 985 | /** Convert the supplied NSDate to NSString, using the current database formatter. 986 | 987 | @param date `NSDate` of date to convert to `NSString`. 988 | 989 | @return The `NSString` representation of the date; `nil` if no formatter is set. 990 | 991 | @see hasDateFormatter 992 | @see setDateFormat: 993 | @see dateFromString: 994 | @see stringFromDate: 995 | @see storeableDateFormat: 996 | */ 997 | 998 | - (NSString *)stringFromDate:(NSDate *)date; 999 | 1000 | @end 1001 | 1002 | 1003 | /** Objective-C wrapper for `sqlite3_stmt` 1004 | 1005 | This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `` and `` only. 1006 | 1007 | ### See also 1008 | 1009 | - `` 1010 | - `` 1011 | - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) 1012 | */ 1013 | 1014 | @interface FMStatement : NSObject { 1015 | sqlite3_stmt *_statement; 1016 | NSString *_query; 1017 | long _useCount; 1018 | BOOL _inUse; 1019 | } 1020 | 1021 | ///----------------- 1022 | /// @name Properties 1023 | ///----------------- 1024 | 1025 | /** Usage count */ 1026 | 1027 | @property (atomic, assign) long useCount; 1028 | 1029 | /** SQL statement */ 1030 | 1031 | @property (atomic, retain) NSString *query; 1032 | 1033 | /** SQLite sqlite3_stmt 1034 | 1035 | @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) 1036 | */ 1037 | 1038 | @property (atomic, assign) sqlite3_stmt *statement; 1039 | 1040 | /** Indication of whether the statement is in use */ 1041 | 1042 | @property (atomic, assign) BOOL inUse; 1043 | 1044 | ///---------------------------- 1045 | /// @name Closing and Resetting 1046 | ///---------------------------- 1047 | 1048 | /** Close statement */ 1049 | 1050 | - (void)close; 1051 | 1052 | /** Reset statement */ 1053 | 1054 | - (void)reset; 1055 | 1056 | @end 1057 | 1058 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMDatabaseAdditions.h: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseAdditions.h 3 | // fmdb 4 | // 5 | // Created by August Mueller on 10/30/05. 6 | // Copyright 2005 Flying Meat Inc.. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "FMDatabase.h" 11 | 12 | 13 | /** Category of additions for `` class. 14 | 15 | ### See also 16 | 17 | - `` 18 | */ 19 | 20 | @interface FMDatabase (FMDatabaseAdditions) 21 | 22 | ///---------------------------------------- 23 | /// @name Return results of SQL to variable 24 | ///---------------------------------------- 25 | 26 | /** Return `int` value for query 27 | 28 | @param query The SQL query to be performed. 29 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 30 | 31 | @return `int` value. 32 | */ 33 | 34 | - (int)intForQuery:(NSString*)query, ...; 35 | 36 | /** Return `long` value for query 37 | 38 | @param query The SQL query to be performed. 39 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 40 | 41 | @return `long` value. 42 | */ 43 | 44 | - (long)longForQuery:(NSString*)query, ...; 45 | 46 | /** Return `BOOL` value for query 47 | 48 | @param query The SQL query to be performed. 49 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 50 | 51 | @return `BOOL` value. 52 | */ 53 | 54 | - (BOOL)boolForQuery:(NSString*)query, ...; 55 | 56 | /** Return `double` value for query 57 | 58 | @param query The SQL query to be performed. 59 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 60 | 61 | @return `double` value. 62 | */ 63 | 64 | - (double)doubleForQuery:(NSString*)query, ...; 65 | 66 | /** Return `NSString` value for query 67 | 68 | @param query The SQL query to be performed. 69 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 70 | 71 | @return `NSString` value. 72 | */ 73 | 74 | - (NSString*)stringForQuery:(NSString*)query, ...; 75 | 76 | /** Return `NSData` value for query 77 | 78 | @param query The SQL query to be performed. 79 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 80 | 81 | @return `NSData` value. 82 | */ 83 | 84 | - (NSData*)dataForQuery:(NSString*)query, ...; 85 | 86 | /** Return `NSDate` value for query 87 | 88 | @param query The SQL query to be performed. 89 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 90 | 91 | @return `NSDate` value. 92 | */ 93 | 94 | - (NSDate*)dateForQuery:(NSString*)query, ...; 95 | 96 | 97 | // Notice that there's no dataNoCopyForQuery:. 98 | // That would be a bad idea, because we close out the result set, and then what 99 | // happens to the data that we just didn't copy? Who knows, not I. 100 | 101 | 102 | ///-------------------------------- 103 | /// @name Schema related operations 104 | ///-------------------------------- 105 | 106 | /** Does table exist in database? 107 | 108 | @param tableName The name of the table being looked for. 109 | 110 | @return `YES` if table found; `NO` if not found. 111 | */ 112 | 113 | - (BOOL)tableExists:(NSString*)tableName; 114 | 115 | /** The schema of the database. 116 | 117 | This will be the schema for the entire database. For each entity, each row of the result set will include the following fields: 118 | 119 | - `type` - The type of entity (e.g. table, index, view, or trigger) 120 | - `name` - The name of the object 121 | - `tbl_name` - The name of the table to which the object references 122 | - `rootpage` - The page number of the root b-tree page for tables and indices 123 | - `sql` - The SQL that created the entity 124 | 125 | @return `FMResultSet` of schema; `nil` on error. 126 | 127 | @see [SQLite File Format](http://www.sqlite.org/fileformat.html) 128 | */ 129 | 130 | - (FMResultSet*)getSchema; 131 | 132 | /** The schema of the database. 133 | 134 | This will be the schema for a particular table as report by SQLite `PRAGMA`, for example: 135 | 136 | PRAGMA table_info('employees') 137 | 138 | This will report: 139 | 140 | - `cid` - The column ID number 141 | - `name` - The name of the column 142 | - `type` - The data type specified for the column 143 | - `notnull` - whether the field is defined as NOT NULL (i.e. values required) 144 | - `dflt_value` - The default value for the column 145 | - `pk` - Whether the field is part of the primary key of the table 146 | 147 | @param tableName The name of the table for whom the schema will be returned. 148 | 149 | @return `FMResultSet` of schema; `nil` on error. 150 | 151 | @see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info) 152 | */ 153 | 154 | - (FMResultSet*)getTableSchema:(NSString*)tableName; 155 | 156 | /** Test to see if particular column exists for particular table in database 157 | 158 | @param columnName The name of the column. 159 | 160 | @param tableName The name of the table. 161 | 162 | @return `YES` if column exists in table in question; `NO` otherwise. 163 | */ 164 | 165 | - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName; 166 | 167 | /** Test to see if particular column exists for particular table in database 168 | 169 | @param columnName The name of the column. 170 | 171 | @param tableName The name of the table. 172 | 173 | @return `YES` if column exists in table in question; `NO` otherwise. 174 | 175 | @see columnExists:inTableWithName: 176 | 177 | @warning Deprecated - use `` instead. 178 | */ 179 | 180 | - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)); 181 | 182 | 183 | /** Validate SQL statement 184 | 185 | This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`. 186 | 187 | @param sql The SQL statement being validated. 188 | 189 | @param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned. 190 | 191 | @return `YES` if validation succeeded without incident; `NO` otherwise. 192 | 193 | */ 194 | 195 | - (BOOL)validateSQL:(NSString*)sql error:(NSError**)error; 196 | 197 | 198 | #if SQLITE_VERSION_NUMBER >= 3007017 199 | 200 | ///----------------------------------- 201 | /// @name Application identifier tasks 202 | ///----------------------------------- 203 | 204 | /** Retrieve application ID 205 | 206 | @return The `uint32_t` numeric value of the application ID. 207 | 208 | @see setApplicationID: 209 | */ 210 | 211 | - (uint32_t)applicationID; 212 | 213 | /** Set the application ID 214 | 215 | @param appID The `uint32_t` numeric value of the application ID. 216 | 217 | @see applicationID 218 | */ 219 | 220 | - (void)setApplicationID:(uint32_t)appID; 221 | 222 | #if TARGET_OS_MAC && !TARGET_OS_IPHONE 223 | /** Retrieve application ID string 224 | 225 | @return The `NSString` value of the application ID. 226 | 227 | @see setApplicationIDString: 228 | */ 229 | 230 | 231 | - (NSString*)applicationIDString; 232 | 233 | /** Set the application ID string 234 | 235 | @param string The `NSString` value of the application ID. 236 | 237 | @see applicationIDString 238 | */ 239 | 240 | - (void)setApplicationIDString:(NSString*)string; 241 | #endif 242 | 243 | #endif 244 | 245 | ///----------------------------------- 246 | /// @name user version identifier tasks 247 | ///----------------------------------- 248 | 249 | /** Retrieve user version 250 | 251 | @return The `uint32_t` numeric value of the user version. 252 | 253 | @see setUserVersion: 254 | */ 255 | 256 | - (uint32_t)userVersion; 257 | 258 | /** Set the user-version 259 | 260 | @param version The `uint32_t` numeric value of the user version. 261 | 262 | @see userVersion 263 | */ 264 | 265 | - (void)setUserVersion:(uint32_t)version; 266 | 267 | @end 268 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMDatabaseAdditions.m: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseAdditions.m 3 | // fmdb 4 | // 5 | // Created by August Mueller on 10/30/05. 6 | // Copyright 2005 Flying Meat Inc.. All rights reserved. 7 | // 8 | 9 | #import "FMDatabase.h" 10 | #import "FMDatabaseAdditions.h" 11 | #import "TargetConditionals.h" 12 | 13 | @interface FMDatabase (PrivateStuff) 14 | - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; 15 | @end 16 | 17 | @implementation FMDatabase (FMDatabaseAdditions) 18 | 19 | #define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \ 20 | va_list args; \ 21 | va_start(args, query); \ 22 | FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \ 23 | va_end(args); \ 24 | if (![resultSet next]) { return (type)0; } \ 25 | type ret = [resultSet sel:0]; \ 26 | [resultSet close]; \ 27 | [resultSet setParentDB:nil]; \ 28 | return ret; 29 | 30 | 31 | - (NSString*)stringForQuery:(NSString*)query, ... { 32 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex); 33 | } 34 | 35 | - (int)intForQuery:(NSString*)query, ... { 36 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex); 37 | } 38 | 39 | - (long)longForQuery:(NSString*)query, ... { 40 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex); 41 | } 42 | 43 | - (BOOL)boolForQuery:(NSString*)query, ... { 44 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex); 45 | } 46 | 47 | - (double)doubleForQuery:(NSString*)query, ... { 48 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex); 49 | } 50 | 51 | - (NSData*)dataForQuery:(NSString*)query, ... { 52 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex); 53 | } 54 | 55 | - (NSDate*)dateForQuery:(NSString*)query, ... { 56 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex); 57 | } 58 | 59 | 60 | - (BOOL)tableExists:(NSString*)tableName { 61 | 62 | tableName = [tableName lowercaseString]; 63 | 64 | FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName]; 65 | 66 | //if at least one next exists, table exists 67 | BOOL returnBool = [rs next]; 68 | 69 | //close and free object 70 | [rs close]; 71 | 72 | return returnBool; 73 | } 74 | 75 | /* 76 | get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] 77 | check if table exist in database (patch from OZLB) 78 | */ 79 | - (FMResultSet*)getSchema { 80 | 81 | //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] 82 | FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"]; 83 | 84 | return rs; 85 | } 86 | 87 | /* 88 | get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] 89 | */ 90 | - (FMResultSet*)getTableSchema:(NSString*)tableName { 91 | 92 | //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] 93 | FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]]; 94 | 95 | return rs; 96 | } 97 | 98 | - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName { 99 | 100 | BOOL returnBool = NO; 101 | 102 | tableName = [tableName lowercaseString]; 103 | columnName = [columnName lowercaseString]; 104 | 105 | FMResultSet *rs = [self getTableSchema:tableName]; 106 | 107 | //check if column is present in table schema 108 | while ([rs next]) { 109 | if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) { 110 | returnBool = YES; 111 | break; 112 | } 113 | } 114 | 115 | //If this is not done FMDatabase instance stays out of pool 116 | [rs close]; 117 | 118 | return returnBool; 119 | } 120 | 121 | 122 | #if SQLITE_VERSION_NUMBER >= 3007017 123 | 124 | - (uint32_t)applicationID { 125 | 126 | uint32_t r = 0; 127 | 128 | FMResultSet *rs = [self executeQuery:@"pragma application_id"]; 129 | 130 | if ([rs next]) { 131 | r = (uint32_t)[rs longLongIntForColumnIndex:0]; 132 | } 133 | 134 | [rs close]; 135 | 136 | return r; 137 | } 138 | 139 | - (void)setApplicationID:(uint32_t)appID { 140 | NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; 141 | FMResultSet *rs = [self executeQuery:query]; 142 | [rs next]; 143 | [rs close]; 144 | } 145 | 146 | 147 | #if TARGET_OS_MAC && !TARGET_OS_IPHONE 148 | - (NSString*)applicationIDString { 149 | NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); 150 | 151 | assert([s length] == 6); 152 | 153 | s = [s substringWithRange:NSMakeRange(1, 4)]; 154 | 155 | 156 | return s; 157 | 158 | } 159 | 160 | - (void)setApplicationIDString:(NSString*)s { 161 | 162 | if ([s length] != 4) { 163 | NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); 164 | } 165 | 166 | [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; 167 | } 168 | 169 | 170 | #endif 171 | 172 | #endif 173 | 174 | - (uint32_t)userVersion { 175 | uint32_t r = 0; 176 | 177 | FMResultSet *rs = [self executeQuery:@"pragma user_version"]; 178 | 179 | if ([rs next]) { 180 | r = (uint32_t)[rs longLongIntForColumnIndex:0]; 181 | } 182 | 183 | [rs close]; 184 | return r; 185 | } 186 | 187 | - (void)setUserVersion:(uint32_t)version { 188 | NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version]; 189 | FMResultSet *rs = [self executeQuery:query]; 190 | [rs next]; 191 | [rs close]; 192 | } 193 | 194 | #pragma clang diagnostic push 195 | #pragma clang diagnostic ignored "-Wdeprecated-implementations" 196 | 197 | - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) { 198 | return [self columnExists:columnName inTableWithName:tableName]; 199 | } 200 | 201 | #pragma clang diagnostic pop 202 | 203 | 204 | - (BOOL)validateSQL:(NSString*)sql error:(NSError**)error { 205 | sqlite3_stmt *pStmt = NULL; 206 | BOOL validationSucceeded = YES; 207 | 208 | int rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); 209 | if (rc != SQLITE_OK) { 210 | validationSucceeded = NO; 211 | if (error) { 212 | *error = [NSError errorWithDomain:NSCocoaErrorDomain 213 | code:[self lastErrorCode] 214 | userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] 215 | forKey:NSLocalizedDescriptionKey]]; 216 | } 217 | } 218 | 219 | sqlite3_finalize(pStmt); 220 | 221 | return validationSucceeded; 222 | } 223 | 224 | @end 225 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMDatabasePool.h: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabasePool.h 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "sqlite3.h" 11 | 12 | @class FMDatabase; 13 | 14 | /** Pool of `` objects. 15 | 16 | ### See also 17 | 18 | - `` 19 | - `` 20 | 21 | @warning Before using `FMDatabasePool`, please consider using `` instead. 22 | 23 | If you really really really know what you're doing and `FMDatabasePool` is what 24 | you really really need (ie, you're using a read only database), OK you can use 25 | it. But just be careful not to deadlock! 26 | 27 | For an example on deadlocking, search for: 28 | `ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD` 29 | in the main.m file. 30 | */ 31 | 32 | @interface FMDatabasePool : NSObject { 33 | NSString *_path; 34 | 35 | dispatch_queue_t _lockQueue; 36 | 37 | NSMutableArray *_databaseInPool; 38 | NSMutableArray *_databaseOutPool; 39 | 40 | __unsafe_unretained id _delegate; 41 | 42 | NSUInteger _maximumNumberOfDatabasesToCreate; 43 | int _openFlags; 44 | } 45 | 46 | /** Database path */ 47 | 48 | @property (atomic, retain) NSString *path; 49 | 50 | /** Delegate object */ 51 | 52 | @property (atomic, assign) id delegate; 53 | 54 | /** Maximum number of databases to create */ 55 | 56 | @property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate; 57 | 58 | /** Open flags */ 59 | 60 | @property (atomic, readonly) int openFlags; 61 | 62 | 63 | ///--------------------- 64 | /// @name Initialization 65 | ///--------------------- 66 | 67 | /** Create pool using path. 68 | 69 | @param aPath The file path of the database. 70 | 71 | @return The `FMDatabasePool` object. `nil` on error. 72 | */ 73 | 74 | + (instancetype)databasePoolWithPath:(NSString*)aPath; 75 | 76 | /** Create pool using path and specified flags 77 | 78 | @param aPath The file path of the database. 79 | @param openFlags Flags passed to the openWithFlags method of the database 80 | 81 | @return The `FMDatabasePool` object. `nil` on error. 82 | */ 83 | 84 | + (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags; 85 | 86 | /** Create pool using path. 87 | 88 | @param aPath The file path of the database. 89 | 90 | @return The `FMDatabasePool` object. `nil` on error. 91 | */ 92 | 93 | - (instancetype)initWithPath:(NSString*)aPath; 94 | 95 | /** Create pool using path and specified flags. 96 | 97 | @param aPath The file path of the database. 98 | @param openFlags Flags passed to the openWithFlags method of the database 99 | 100 | @return The `FMDatabasePool` object. `nil` on error. 101 | */ 102 | 103 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; 104 | 105 | ///------------------------------------------------ 106 | /// @name Keeping track of checked in/out databases 107 | ///------------------------------------------------ 108 | 109 | /** Number of checked-in databases in pool 110 | 111 | @returns Number of databases 112 | */ 113 | 114 | - (NSUInteger)countOfCheckedInDatabases; 115 | 116 | /** Number of checked-out databases in pool 117 | 118 | @returns Number of databases 119 | */ 120 | 121 | - (NSUInteger)countOfCheckedOutDatabases; 122 | 123 | /** Total number of databases in pool 124 | 125 | @returns Number of databases 126 | */ 127 | 128 | - (NSUInteger)countOfOpenDatabases; 129 | 130 | /** Release all databases in pool */ 131 | 132 | - (void)releaseAllDatabases; 133 | 134 | ///------------------------------------------ 135 | /// @name Perform database operations in pool 136 | ///------------------------------------------ 137 | 138 | /** Synchronously perform database operations in pool. 139 | 140 | @param block The code to be run on the `FMDatabasePool` pool. 141 | */ 142 | 143 | - (void)inDatabase:(void (^)(FMDatabase *db))block; 144 | 145 | /** Synchronously perform database operations in pool using transaction. 146 | 147 | @param block The code to be run on the `FMDatabasePool` pool. 148 | */ 149 | 150 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 151 | 152 | /** Synchronously perform database operations in pool using deferred transaction. 153 | 154 | @param block The code to be run on the `FMDatabasePool` pool. 155 | */ 156 | 157 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 158 | 159 | #if SQLITE_VERSION_NUMBER >= 3007000 160 | 161 | /** Synchronously perform database operations in pool using save point. 162 | 163 | @param block The code to be run on the `FMDatabasePool` pool. 164 | 165 | @return `NSError` object if error; `nil` if successful. 166 | 167 | @warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead. 168 | */ 169 | 170 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; 171 | #endif 172 | 173 | @end 174 | 175 | 176 | /** FMDatabasePool delegate category 177 | 178 | This is a category that defines the protocol for the FMDatabasePool delegate 179 | */ 180 | 181 | @interface NSObject (FMDatabasePoolDelegate) 182 | 183 | /** Asks the delegate whether database should be added to the pool. 184 | 185 | @param pool The `FMDatabasePool` object. 186 | @param database The `FMDatabase` object. 187 | 188 | @return `YES` if it should add database to pool; `NO` if not. 189 | 190 | */ 191 | 192 | - (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database; 193 | 194 | /** Tells the delegate that database was added to the pool. 195 | 196 | @param pool The `FMDatabasePool` object. 197 | @param database The `FMDatabase` object. 198 | 199 | */ 200 | 201 | - (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database; 202 | 203 | @end 204 | 205 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMDatabasePool.m: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabasePool.m 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import "FMDatabasePool.h" 10 | #import "FMDatabase.h" 11 | 12 | @interface FMDatabasePool() 13 | 14 | - (void)pushDatabaseBackInPool:(FMDatabase*)db; 15 | - (FMDatabase*)db; 16 | 17 | @end 18 | 19 | 20 | @implementation FMDatabasePool 21 | @synthesize path=_path; 22 | @synthesize delegate=_delegate; 23 | @synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate; 24 | @synthesize openFlags=_openFlags; 25 | 26 | 27 | + (instancetype)databasePoolWithPath:(NSString*)aPath { 28 | return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); 29 | } 30 | 31 | + (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags { 32 | return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]); 33 | } 34 | 35 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { 36 | 37 | self = [super init]; 38 | 39 | if (self != nil) { 40 | _path = [aPath copy]; 41 | _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); 42 | _databaseInPool = FMDBReturnRetained([NSMutableArray array]); 43 | _databaseOutPool = FMDBReturnRetained([NSMutableArray array]); 44 | _openFlags = openFlags; 45 | } 46 | 47 | return self; 48 | } 49 | 50 | - (instancetype)initWithPath:(NSString*)aPath 51 | { 52 | // default flags for sqlite3_open 53 | return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; 54 | } 55 | 56 | - (instancetype)init { 57 | return [self initWithPath:nil]; 58 | } 59 | 60 | 61 | - (void)dealloc { 62 | 63 | _delegate = 0x00; 64 | FMDBRelease(_path); 65 | FMDBRelease(_databaseInPool); 66 | FMDBRelease(_databaseOutPool); 67 | 68 | if (_lockQueue) { 69 | FMDBDispatchQueueRelease(_lockQueue); 70 | _lockQueue = 0x00; 71 | } 72 | #if ! __has_feature(objc_arc) 73 | [super dealloc]; 74 | #endif 75 | } 76 | 77 | 78 | - (void)executeLocked:(void (^)(void))aBlock { 79 | dispatch_sync(_lockQueue, aBlock); 80 | } 81 | 82 | - (void)pushDatabaseBackInPool:(FMDatabase*)db { 83 | 84 | if (!db) { // db can be null if we set an upper bound on the # of databases to create. 85 | return; 86 | } 87 | 88 | [self executeLocked:^() { 89 | 90 | if ([_databaseInPool containsObject:db]) { 91 | [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise]; 92 | } 93 | 94 | [_databaseInPool addObject:db]; 95 | [_databaseOutPool removeObject:db]; 96 | 97 | }]; 98 | } 99 | 100 | - (FMDatabase*)db { 101 | 102 | __block FMDatabase *db; 103 | 104 | 105 | [self executeLocked:^() { 106 | db = [_databaseInPool lastObject]; 107 | 108 | BOOL shouldNotifyDelegate = NO; 109 | 110 | if (db) { 111 | [_databaseOutPool addObject:db]; 112 | [_databaseInPool removeLastObject]; 113 | } 114 | else { 115 | 116 | if (_maximumNumberOfDatabasesToCreate) { 117 | NSUInteger currentCount = [_databaseOutPool count] + [_databaseInPool count]; 118 | 119 | if (currentCount >= _maximumNumberOfDatabasesToCreate) { 120 | NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount); 121 | return; 122 | } 123 | } 124 | 125 | db = [FMDatabase databaseWithPath:_path]; 126 | shouldNotifyDelegate = YES; 127 | } 128 | 129 | //This ensures that the db is opened before returning 130 | #if SQLITE_VERSION_NUMBER >= 3005000 131 | BOOL success = [db openWithFlags:_openFlags]; 132 | #else 133 | BOOL success = [db open]; 134 | #endif 135 | if (success) { 136 | if ([_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![_delegate databasePool:self shouldAddDatabaseToPool:db]) { 137 | [db close]; 138 | db = 0x00; 139 | } 140 | else { 141 | //It should not get added in the pool twice if lastObject was found 142 | if (![_databaseOutPool containsObject:db]) { 143 | [_databaseOutPool addObject:db]; 144 | 145 | if (shouldNotifyDelegate && [_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) { 146 | [_delegate databasePool:self didAddDatabase:db]; 147 | } 148 | } 149 | } 150 | } 151 | else { 152 | NSLog(@"Could not open up the database at path %@", _path); 153 | db = 0x00; 154 | } 155 | }]; 156 | 157 | return db; 158 | } 159 | 160 | - (NSUInteger)countOfCheckedInDatabases { 161 | 162 | __block NSUInteger count; 163 | 164 | [self executeLocked:^() { 165 | count = [_databaseInPool count]; 166 | }]; 167 | 168 | return count; 169 | } 170 | 171 | - (NSUInteger)countOfCheckedOutDatabases { 172 | 173 | __block NSUInteger count; 174 | 175 | [self executeLocked:^() { 176 | count = [_databaseOutPool count]; 177 | }]; 178 | 179 | return count; 180 | } 181 | 182 | - (NSUInteger)countOfOpenDatabases { 183 | __block NSUInteger count; 184 | 185 | [self executeLocked:^() { 186 | count = [_databaseOutPool count] + [_databaseInPool count]; 187 | }]; 188 | 189 | return count; 190 | } 191 | 192 | - (void)releaseAllDatabases { 193 | [self executeLocked:^() { 194 | [_databaseOutPool removeAllObjects]; 195 | [_databaseInPool removeAllObjects]; 196 | }]; 197 | } 198 | 199 | - (void)inDatabase:(void (^)(FMDatabase *db))block { 200 | 201 | FMDatabase *db = [self db]; 202 | 203 | block(db); 204 | 205 | [self pushDatabaseBackInPool:db]; 206 | } 207 | 208 | - (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { 209 | 210 | BOOL shouldRollback = NO; 211 | 212 | FMDatabase *db = [self db]; 213 | 214 | if (useDeferred) { 215 | [db beginDeferredTransaction]; 216 | } 217 | else { 218 | [db beginTransaction]; 219 | } 220 | 221 | 222 | block(db, &shouldRollback); 223 | 224 | if (shouldRollback) { 225 | [db rollback]; 226 | } 227 | else { 228 | [db commit]; 229 | } 230 | 231 | [self pushDatabaseBackInPool:db]; 232 | } 233 | 234 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 235 | [self beginTransaction:YES withBlock:block]; 236 | } 237 | 238 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 239 | [self beginTransaction:NO withBlock:block]; 240 | } 241 | #if SQLITE_VERSION_NUMBER >= 3007000 242 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { 243 | 244 | static unsigned long savePointIdx = 0; 245 | 246 | NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; 247 | 248 | BOOL shouldRollback = NO; 249 | 250 | FMDatabase *db = [self db]; 251 | 252 | NSError *err = 0x00; 253 | 254 | if (![db startSavePointWithName:name error:&err]) { 255 | [self pushDatabaseBackInPool:db]; 256 | return err; 257 | } 258 | 259 | block(db, &shouldRollback); 260 | 261 | if (shouldRollback) { 262 | // We need to rollback and release this savepoint to remove it 263 | [db rollbackToSavePointWithName:name error:&err]; 264 | } 265 | [db releaseSavePointWithName:name error:&err]; 266 | 267 | [self pushDatabaseBackInPool:db]; 268 | 269 | return err; 270 | } 271 | #endif 272 | 273 | @end 274 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMDatabaseQueue.h: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseQueue.h 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "sqlite3.h" 11 | 12 | @class FMDatabase; 13 | 14 | /** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`. 15 | 16 | Using a single instance of `` from multiple threads at once is a bad idea. It has always been OK to make a `` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. 17 | 18 | Instead, use `FMDatabaseQueue`. Here's how to use it: 19 | 20 | First, make your queue. 21 | 22 | FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; 23 | 24 | Then use it like so: 25 | 26 | [queue inDatabase:^(FMDatabase *db) { 27 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; 28 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; 29 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; 30 | 31 | FMResultSet *rs = [db executeQuery:@"select * from foo"]; 32 | while ([rs next]) { 33 | //… 34 | } 35 | }]; 36 | 37 | An easy way to wrap things up in a transaction can be done like this: 38 | 39 | [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { 40 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; 41 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; 42 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; 43 | 44 | if (whoopsSomethingWrongHappened) { 45 | *rollback = YES; 46 | return; 47 | } 48 | // etc… 49 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; 50 | }]; 51 | 52 | `FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. 53 | 54 | ### See also 55 | 56 | - `` 57 | 58 | @warning Do not instantiate a single `` object and use it across multiple threads. Use `FMDatabaseQueue` instead. 59 | 60 | @warning The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. 61 | 62 | */ 63 | 64 | @interface FMDatabaseQueue : NSObject { 65 | NSString *_path; 66 | dispatch_queue_t _queue; 67 | FMDatabase *_db; 68 | int _openFlags; 69 | } 70 | 71 | /** Path of database */ 72 | 73 | @property (atomic, retain) NSString *path; 74 | 75 | /** Open flags */ 76 | 77 | @property (atomic, readonly) int openFlags; 78 | 79 | ///---------------------------------------------------- 80 | /// @name Initialization, opening, and closing of queue 81 | ///---------------------------------------------------- 82 | 83 | /** Create queue using path. 84 | 85 | @param aPath The file path of the database. 86 | 87 | @return The `FMDatabaseQueue` object. `nil` on error. 88 | */ 89 | 90 | + (instancetype)databaseQueueWithPath:(NSString*)aPath; 91 | 92 | /** Create queue using path and specified flags. 93 | 94 | @param aPath The file path of the database. 95 | @param openFlags Flags passed to the openWithFlags method of the database 96 | 97 | @return The `FMDatabaseQueue` object. `nil` on error. 98 | */ 99 | + (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags; 100 | 101 | /** Create queue using path. 102 | 103 | @param aPath The file path of the database. 104 | 105 | @return The `FMDatabaseQueue` object. `nil` on error. 106 | */ 107 | 108 | - (instancetype)initWithPath:(NSString*)aPath; 109 | 110 | /** Create queue using path and specified flags. 111 | 112 | @param aPath The file path of the database. 113 | @param openFlags Flags passed to the openWithFlags method of the database 114 | 115 | @return The `FMDatabaseQueue` object. `nil` on error. 116 | */ 117 | 118 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; 119 | 120 | /** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. 121 | 122 | Subclasses can override this method to return specified Class of 'FMDatabase' subclass. 123 | 124 | @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. 125 | */ 126 | 127 | + (Class)databaseClass; 128 | 129 | /** Close database used by queue. */ 130 | 131 | - (void)close; 132 | 133 | ///----------------------------------------------- 134 | /// @name Dispatching database operations to queue 135 | ///----------------------------------------------- 136 | 137 | /** Synchronously perform database operations on queue. 138 | 139 | @param block The code to be run on the queue of `FMDatabaseQueue` 140 | */ 141 | 142 | - (void)inDatabase:(void (^)(FMDatabase *db))block; 143 | 144 | /** Synchronously perform database operations on queue, using transactions. 145 | 146 | @param block The code to be run on the queue of `FMDatabaseQueue` 147 | */ 148 | 149 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 150 | 151 | /** Synchronously perform database operations on queue, using deferred transactions. 152 | 153 | @param block The code to be run on the queue of `FMDatabaseQueue` 154 | */ 155 | 156 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 157 | 158 | ///----------------------------------------------- 159 | /// @name Dispatching database operations to queue 160 | ///----------------------------------------------- 161 | 162 | /** Synchronously perform database operations using save point. 163 | 164 | @param block The code to be run on the queue of `FMDatabaseQueue` 165 | */ 166 | 167 | #if SQLITE_VERSION_NUMBER >= 3007000 168 | // NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. 169 | // If you need to nest, use FMDatabase's startSavePointWithName:error: instead. 170 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; 171 | #endif 172 | 173 | @end 174 | 175 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMDatabaseQueue.m: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseQueue.m 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import "FMDatabaseQueue.h" 10 | #import "FMDatabase.h" 11 | 12 | /* 13 | 14 | Note: we call [self retain]; before using dispatch_sync, just incase 15 | FMDatabaseQueue is released on another thread and we're in the middle of doing 16 | something in dispatch_sync 17 | 18 | */ 19 | 20 | /* 21 | * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses. 22 | * This in turn is used for deadlock detection by seeing if inDatabase: is called on 23 | * the queue's dispatch queue, which should not happen and causes a deadlock. 24 | */ 25 | static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey; 26 | 27 | @implementation FMDatabaseQueue 28 | 29 | @synthesize path = _path; 30 | @synthesize openFlags = _openFlags; 31 | 32 | + (instancetype)databaseQueueWithPath:(NSString*)aPath { 33 | 34 | FMDatabaseQueue *q = [[self alloc] initWithPath:aPath]; 35 | 36 | FMDBAutorelease(q); 37 | 38 | return q; 39 | } 40 | 41 | + (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags { 42 | 43 | FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; 44 | 45 | FMDBAutorelease(q); 46 | 47 | return q; 48 | } 49 | 50 | + (Class)databaseClass { 51 | return [FMDatabase class]; 52 | } 53 | 54 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { 55 | 56 | self = [super init]; 57 | 58 | if (self != nil) { 59 | 60 | _db = [[[self class] databaseClass] databaseWithPath:aPath]; 61 | FMDBRetain(_db); 62 | 63 | #if SQLITE_VERSION_NUMBER >= 3005000 64 | BOOL success = [_db openWithFlags:openFlags]; 65 | #else 66 | BOOL success = [_db open]; 67 | #endif 68 | if (!success) { 69 | NSLog(@"Could not create database queue for path %@", aPath); 70 | FMDBRelease(self); 71 | return 0x00; 72 | } 73 | 74 | _path = FMDBReturnRetained(aPath); 75 | 76 | _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); 77 | dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL); 78 | _openFlags = openFlags; 79 | } 80 | 81 | return self; 82 | } 83 | 84 | - (instancetype)initWithPath:(NSString*)aPath { 85 | 86 | // default flags for sqlite3_open 87 | return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; 88 | } 89 | 90 | - (instancetype)init { 91 | return [self initWithPath:nil]; 92 | } 93 | 94 | 95 | - (void)dealloc { 96 | 97 | FMDBRelease(_db); 98 | FMDBRelease(_path); 99 | 100 | if (_queue) { 101 | FMDBDispatchQueueRelease(_queue); 102 | _queue = 0x00; 103 | } 104 | #if ! __has_feature(objc_arc) 105 | [super dealloc]; 106 | #endif 107 | } 108 | 109 | - (void)close { 110 | FMDBRetain(self); 111 | dispatch_sync(_queue, ^() { 112 | [_db close]; 113 | FMDBRelease(_db); 114 | _db = 0x00; 115 | }); 116 | FMDBRelease(self); 117 | } 118 | 119 | - (FMDatabase*)database { 120 | if (!_db) { 121 | _db = FMDBReturnRetained([FMDatabase databaseWithPath:_path]); 122 | 123 | #if SQLITE_VERSION_NUMBER >= 3005000 124 | BOOL success = [_db openWithFlags:_openFlags]; 125 | #else 126 | BOOL success = [db open]; 127 | #endif 128 | if (!success) { 129 | NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path); 130 | FMDBRelease(_db); 131 | _db = 0x00; 132 | return 0x00; 133 | } 134 | } 135 | 136 | return _db; 137 | } 138 | 139 | - (void)inDatabase:(void (^)(FMDatabase *db))block { 140 | /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue 141 | * and then check it against self to make sure we're not about to deadlock. */ 142 | FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey); 143 | assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock"); 144 | 145 | FMDBRetain(self); 146 | 147 | dispatch_sync(_queue, ^() { 148 | 149 | FMDatabase *db = [self database]; 150 | block(db); 151 | 152 | if ([db hasOpenResultSets]) { 153 | NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]"); 154 | 155 | #ifdef DEBUG 156 | NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]); 157 | for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { 158 | FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; 159 | NSLog(@"query: '%@'", [rs query]); 160 | } 161 | #endif 162 | } 163 | }); 164 | 165 | FMDBRelease(self); 166 | } 167 | 168 | 169 | - (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { 170 | FMDBRetain(self); 171 | dispatch_sync(_queue, ^() { 172 | 173 | BOOL shouldRollback = NO; 174 | 175 | if (useDeferred) { 176 | [[self database] beginDeferredTransaction]; 177 | } 178 | else { 179 | [[self database] beginTransaction]; 180 | } 181 | 182 | block([self database], &shouldRollback); 183 | 184 | if (shouldRollback) { 185 | [[self database] rollback]; 186 | } 187 | else { 188 | [[self database] commit]; 189 | } 190 | }); 191 | 192 | FMDBRelease(self); 193 | } 194 | 195 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 196 | [self beginTransaction:YES withBlock:block]; 197 | } 198 | 199 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 200 | [self beginTransaction:NO withBlock:block]; 201 | } 202 | 203 | #if SQLITE_VERSION_NUMBER >= 3007000 204 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { 205 | 206 | static unsigned long savePointIdx = 0; 207 | __block NSError *err = 0x00; 208 | FMDBRetain(self); 209 | dispatch_sync(_queue, ^() { 210 | 211 | NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; 212 | 213 | BOOL shouldRollback = NO; 214 | 215 | if ([[self database] startSavePointWithName:name error:&err]) { 216 | 217 | block([self database], &shouldRollback); 218 | 219 | if (shouldRollback) { 220 | // We need to rollback and release this savepoint to remove it 221 | [[self database] rollbackToSavePointWithName:name error:&err]; 222 | } 223 | [[self database] releaseSavePointWithName:name error:&err]; 224 | 225 | } 226 | }); 227 | FMDBRelease(self); 228 | return err; 229 | } 230 | #endif 231 | 232 | @end 233 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMResultSet.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "sqlite3.h" 3 | 4 | #ifndef __has_feature // Optional. 5 | #define __has_feature(x) 0 // Compatibility with non-clang compilers. 6 | #endif 7 | 8 | #ifndef NS_RETURNS_NOT_RETAINED 9 | #if __has_feature(attribute_ns_returns_not_retained) 10 | #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) 11 | #else 12 | #define NS_RETURNS_NOT_RETAINED 13 | #endif 14 | #endif 15 | 16 | @class FMDatabase; 17 | @class FMStatement; 18 | 19 | /** Represents the results of executing a query on an ``. 20 | 21 | ### See also 22 | 23 | - `` 24 | */ 25 | 26 | @interface FMResultSet : NSObject { 27 | FMDatabase *_parentDB; 28 | FMStatement *_statement; 29 | 30 | NSString *_query; 31 | NSMutableDictionary *_columnNameToIndexMap; 32 | } 33 | 34 | ///----------------- 35 | /// @name Properties 36 | ///----------------- 37 | 38 | /** Executed query */ 39 | 40 | @property (atomic, retain) NSString *query; 41 | 42 | /** `NSMutableDictionary` mapping column names to numeric index */ 43 | 44 | @property (readonly) NSMutableDictionary *columnNameToIndexMap; 45 | 46 | /** `FMStatement` used by result set. */ 47 | 48 | @property (atomic, retain) FMStatement *statement; 49 | 50 | ///------------------------------------ 51 | /// @name Creating and closing database 52 | ///------------------------------------ 53 | 54 | /** Create result set from `` 55 | 56 | @param statement A `` to be performed 57 | 58 | @param aDB A `` to be used 59 | 60 | @return A `FMResultSet` on success; `nil` on failure 61 | */ 62 | 63 | + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB; 64 | 65 | /** Close result set */ 66 | 67 | - (void)close; 68 | 69 | - (void)setParentDB:(FMDatabase *)newDb; 70 | 71 | ///--------------------------------------- 72 | /// @name Iterating through the result set 73 | ///--------------------------------------- 74 | 75 | /** Retrieve next row for result set. 76 | 77 | You must always invoke `next` before attempting to access the values returned in a query, even if you're only expecting one. 78 | 79 | @return `YES` if row successfully retrieved; `NO` if end of result set reached 80 | 81 | @see hasAnotherRow 82 | */ 83 | 84 | - (BOOL)next; 85 | 86 | /** Did the last call to `` succeed in retrieving another row? 87 | 88 | @return `YES` if the last call to `` succeeded in retrieving another record; `NO` if not. 89 | 90 | @see next 91 | 92 | @warning The `hasAnotherRow` method must follow a call to ``. If the previous database interaction was something other than a call to `next`, then this method may return `NO`, whether there is another row of data or not. 93 | */ 94 | 95 | - (BOOL)hasAnotherRow; 96 | 97 | ///--------------------------------------------- 98 | /// @name Retrieving information from result set 99 | ///--------------------------------------------- 100 | 101 | /** How many columns in result set 102 | 103 | @return Integer value of the number of columns. 104 | */ 105 | 106 | - (int)columnCount; 107 | 108 | /** Column index for column name 109 | 110 | @param columnName `NSString` value of the name of the column. 111 | 112 | @return Zero-based index for column. 113 | */ 114 | 115 | - (int)columnIndexForName:(NSString*)columnName; 116 | 117 | /** Column name for column index 118 | 119 | @param columnIdx Zero-based index for column. 120 | 121 | @return columnName `NSString` value of the name of the column. 122 | */ 123 | 124 | - (NSString*)columnNameForIndex:(int)columnIdx; 125 | 126 | /** Result set integer value for column. 127 | 128 | @param columnName `NSString` value of the name of the column. 129 | 130 | @return `int` value of the result set's column. 131 | */ 132 | 133 | - (int)intForColumn:(NSString*)columnName; 134 | 135 | /** Result set integer value for column. 136 | 137 | @param columnIdx Zero-based index for column. 138 | 139 | @return `int` value of the result set's column. 140 | */ 141 | 142 | - (int)intForColumnIndex:(int)columnIdx; 143 | 144 | /** Result set `long` value for column. 145 | 146 | @param columnName `NSString` value of the name of the column. 147 | 148 | @return `long` value of the result set's column. 149 | */ 150 | 151 | - (long)longForColumn:(NSString*)columnName; 152 | 153 | /** Result set long value for column. 154 | 155 | @param columnIdx Zero-based index for column. 156 | 157 | @return `long` value of the result set's column. 158 | */ 159 | 160 | - (long)longForColumnIndex:(int)columnIdx; 161 | 162 | /** Result set `long long int` value for column. 163 | 164 | @param columnName `NSString` value of the name of the column. 165 | 166 | @return `long long int` value of the result set's column. 167 | */ 168 | 169 | - (long long int)longLongIntForColumn:(NSString*)columnName; 170 | 171 | /** Result set `long long int` value for column. 172 | 173 | @param columnIdx Zero-based index for column. 174 | 175 | @return `long long int` value of the result set's column. 176 | */ 177 | 178 | - (long long int)longLongIntForColumnIndex:(int)columnIdx; 179 | 180 | /** Result set `unsigned long long int` value for column. 181 | 182 | @param columnName `NSString` value of the name of the column. 183 | 184 | @return `unsigned long long int` value of the result set's column. 185 | */ 186 | 187 | - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName; 188 | 189 | /** Result set `unsigned long long int` value for column. 190 | 191 | @param columnIdx Zero-based index for column. 192 | 193 | @return `unsigned long long int` value of the result set's column. 194 | */ 195 | 196 | - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx; 197 | 198 | /** Result set `BOOL` value for column. 199 | 200 | @param columnName `NSString` value of the name of the column. 201 | 202 | @return `BOOL` value of the result set's column. 203 | */ 204 | 205 | - (BOOL)boolForColumn:(NSString*)columnName; 206 | 207 | /** Result set `BOOL` value for column. 208 | 209 | @param columnIdx Zero-based index for column. 210 | 211 | @return `BOOL` value of the result set's column. 212 | */ 213 | 214 | - (BOOL)boolForColumnIndex:(int)columnIdx; 215 | 216 | /** Result set `double` value for column. 217 | 218 | @param columnName `NSString` value of the name of the column. 219 | 220 | @return `double` value of the result set's column. 221 | 222 | */ 223 | 224 | - (double)doubleForColumn:(NSString*)columnName; 225 | 226 | /** Result set `double` value for column. 227 | 228 | @param columnIdx Zero-based index for column. 229 | 230 | @return `double` value of the result set's column. 231 | 232 | */ 233 | 234 | - (double)doubleForColumnIndex:(int)columnIdx; 235 | 236 | /** Result set `NSString` value for column. 237 | 238 | @param columnName `NSString` value of the name of the column. 239 | 240 | @return `NSString` value of the result set's column. 241 | 242 | */ 243 | 244 | - (NSString*)stringForColumn:(NSString*)columnName; 245 | 246 | /** Result set `NSString` value for column. 247 | 248 | @param columnIdx Zero-based index for column. 249 | 250 | @return `NSString` value of the result set's column. 251 | */ 252 | 253 | - (NSString*)stringForColumnIndex:(int)columnIdx; 254 | 255 | /** Result set `NSDate` value for column. 256 | 257 | @param columnName `NSString` value of the name of the column. 258 | 259 | @return `NSDate` value of the result set's column. 260 | */ 261 | 262 | - (NSDate*)dateForColumn:(NSString*)columnName; 263 | 264 | /** Result set `NSDate` value for column. 265 | 266 | @param columnIdx Zero-based index for column. 267 | 268 | @return `NSDate` value of the result set's column. 269 | 270 | */ 271 | 272 | - (NSDate*)dateForColumnIndex:(int)columnIdx; 273 | 274 | /** Result set `NSData` value for column. 275 | 276 | This is useful when storing binary data in table (such as image or the like). 277 | 278 | @param columnName `NSString` value of the name of the column. 279 | 280 | @return `NSData` value of the result set's column. 281 | 282 | */ 283 | 284 | - (NSData*)dataForColumn:(NSString*)columnName; 285 | 286 | /** Result set `NSData` value for column. 287 | 288 | @param columnIdx Zero-based index for column. 289 | 290 | @return `NSData` value of the result set's column. 291 | */ 292 | 293 | - (NSData*)dataForColumnIndex:(int)columnIdx; 294 | 295 | /** Result set `(const unsigned char *)` value for column. 296 | 297 | @param columnName `NSString` value of the name of the column. 298 | 299 | @return `(const unsigned char *)` value of the result set's column. 300 | */ 301 | 302 | - (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName; 303 | 304 | /** Result set `(const unsigned char *)` value for column. 305 | 306 | @param columnIdx Zero-based index for column. 307 | 308 | @return `(const unsigned char *)` value of the result set's column. 309 | */ 310 | 311 | - (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx; 312 | 313 | /** Result set object for column. 314 | 315 | @param columnName `NSString` value of the name of the column. 316 | 317 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 318 | 319 | @see objectForKeyedSubscript: 320 | */ 321 | 322 | - (id)objectForColumnName:(NSString*)columnName; 323 | 324 | /** Result set object for column. 325 | 326 | @param columnIdx Zero-based index for column. 327 | 328 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 329 | 330 | @see objectAtIndexedSubscript: 331 | */ 332 | 333 | - (id)objectForColumnIndex:(int)columnIdx; 334 | 335 | /** Result set object for column. 336 | 337 | This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: 338 | 339 | id result = rs[@"employee_name"]; 340 | 341 | This simplified syntax is equivalent to calling: 342 | 343 | id result = [rs objectForKeyedSubscript:@"employee_name"]; 344 | 345 | which is, it turns out, equivalent to calling: 346 | 347 | id result = [rs objectForColumnName:@"employee_name"]; 348 | 349 | @param columnName `NSString` value of the name of the column. 350 | 351 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 352 | */ 353 | 354 | - (id)objectForKeyedSubscript:(NSString *)columnName; 355 | 356 | /** Result set object for column. 357 | 358 | This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: 359 | 360 | id result = rs[0]; 361 | 362 | This simplified syntax is equivalent to calling: 363 | 364 | id result = [rs objectForKeyedSubscript:0]; 365 | 366 | which is, it turns out, equivalent to calling: 367 | 368 | id result = [rs objectForColumnName:0]; 369 | 370 | @param columnIdx Zero-based index for column. 371 | 372 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 373 | */ 374 | 375 | - (id)objectAtIndexedSubscript:(int)columnIdx; 376 | 377 | /** Result set `NSData` value for column. 378 | 379 | @param columnName `NSString` value of the name of the column. 380 | 381 | @return `NSData` value of the result set's column. 382 | 383 | @warning If you are going to use this data after you iterate over the next row, or after you close the 384 | result set, make sure to make a copy of the data first (or just use ``/``) 385 | If you don't, you're going to be in a world of hurt when you try and use the data. 386 | 387 | */ 388 | 389 | - (NSData*)dataNoCopyForColumn:(NSString*)columnName NS_RETURNS_NOT_RETAINED; 390 | 391 | /** Result set `NSData` value for column. 392 | 393 | @param columnIdx Zero-based index for column. 394 | 395 | @return `NSData` value of the result set's column. 396 | 397 | @warning If you are going to use this data after you iterate over the next row, or after you close the 398 | result set, make sure to make a copy of the data first (or just use ``/``) 399 | If you don't, you're going to be in a world of hurt when you try and use the data. 400 | 401 | */ 402 | 403 | - (NSData*)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; 404 | 405 | /** Is the column `NULL`? 406 | 407 | @param columnIdx Zero-based index for column. 408 | 409 | @return `YES` if column is `NULL`; `NO` if not `NULL`. 410 | */ 411 | 412 | - (BOOL)columnIndexIsNull:(int)columnIdx; 413 | 414 | /** Is the column `NULL`? 415 | 416 | @param columnName `NSString` value of the name of the column. 417 | 418 | @return `YES` if column is `NULL`; `NO` if not `NULL`. 419 | */ 420 | 421 | - (BOOL)columnIsNull:(NSString*)columnName; 422 | 423 | 424 | /** Returns a dictionary of the row results mapped to case sensitive keys of the column names. 425 | 426 | @returns `NSDictionary` of the row results. 427 | 428 | @warning The keys to the dictionary are case sensitive of the column names. 429 | */ 430 | 431 | - (NSDictionary*)resultDictionary; 432 | 433 | /** Returns a dictionary of the row results 434 | 435 | @see resultDictionary 436 | 437 | @warning **Deprecated**: Please use `` instead. Also, beware that `` is case sensitive! 438 | */ 439 | 440 | - (NSDictionary*)resultDict __attribute__ ((deprecated)); 441 | 442 | ///----------------------------- 443 | /// @name Key value coding magic 444 | ///----------------------------- 445 | 446 | /** Performs `setValue` to yield support for key value observing. 447 | 448 | @param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe. 449 | 450 | */ 451 | 452 | - (void)kvcMagic:(id)object; 453 | 454 | 455 | @end 456 | 457 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/fmdb/FMResultSet.m: -------------------------------------------------------------------------------- 1 | #import "FMResultSet.h" 2 | #import "FMDatabase.h" 3 | #import "unistd.h" 4 | 5 | @interface FMDatabase () 6 | - (void)resultSetDidClose:(FMResultSet *)resultSet; 7 | @end 8 | 9 | 10 | @implementation FMResultSet 11 | @synthesize query=_query; 12 | @synthesize statement=_statement; 13 | 14 | + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB { 15 | 16 | FMResultSet *rs = [[FMResultSet alloc] init]; 17 | 18 | [rs setStatement:statement]; 19 | [rs setParentDB:aDB]; 20 | 21 | NSParameterAssert(![statement inUse]); 22 | [statement setInUse:YES]; // weak reference 23 | 24 | return FMDBReturnAutoreleased(rs); 25 | } 26 | 27 | - (void)finalize { 28 | [self close]; 29 | [super finalize]; 30 | } 31 | 32 | - (void)dealloc { 33 | [self close]; 34 | 35 | FMDBRelease(_query); 36 | _query = nil; 37 | 38 | FMDBRelease(_columnNameToIndexMap); 39 | _columnNameToIndexMap = nil; 40 | 41 | #if ! __has_feature(objc_arc) 42 | [super dealloc]; 43 | #endif 44 | } 45 | 46 | - (void)close { 47 | [_statement reset]; 48 | FMDBRelease(_statement); 49 | _statement = nil; 50 | 51 | // we don't need this anymore... (i think) 52 | //[_parentDB setInUse:NO]; 53 | [_parentDB resultSetDidClose:self]; 54 | _parentDB = nil; 55 | } 56 | 57 | - (int)columnCount { 58 | return sqlite3_column_count([_statement statement]); 59 | } 60 | 61 | - (NSMutableDictionary *)columnNameToIndexMap { 62 | if (!_columnNameToIndexMap) { 63 | int columnCount = sqlite3_column_count([_statement statement]); 64 | _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount]; 65 | int columnIdx = 0; 66 | for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { 67 | [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx] 68 | forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]]; 69 | } 70 | } 71 | return _columnNameToIndexMap; 72 | } 73 | 74 | - (void)kvcMagic:(id)object { 75 | 76 | int columnCount = sqlite3_column_count([_statement statement]); 77 | 78 | int columnIdx = 0; 79 | for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { 80 | 81 | const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); 82 | 83 | // check for a null row 84 | if (c) { 85 | NSString *s = [NSString stringWithUTF8String:c]; 86 | 87 | [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]]; 88 | } 89 | } 90 | } 91 | 92 | #pragma clang diagnostic push 93 | #pragma clang diagnostic ignored "-Wdeprecated-implementations" 94 | 95 | - (NSDictionary*)resultDict { 96 | 97 | NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); 98 | 99 | if (num_cols > 0) { 100 | NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; 101 | 102 | NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator]; 103 | NSString *columnName = nil; 104 | while ((columnName = [columnNames nextObject])) { 105 | id objectValue = [self objectForColumnName:columnName]; 106 | [dict setObject:objectValue forKey:columnName]; 107 | } 108 | 109 | return FMDBReturnAutoreleased([dict copy]); 110 | } 111 | else { 112 | NSLog(@"Warning: There seem to be no columns in this set."); 113 | } 114 | 115 | return nil; 116 | } 117 | 118 | #pragma clang diagnostic pop 119 | 120 | - (NSDictionary*)resultDictionary { 121 | 122 | NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); 123 | 124 | if (num_cols > 0) { 125 | NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; 126 | 127 | int columnCount = sqlite3_column_count([_statement statement]); 128 | 129 | int columnIdx = 0; 130 | for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { 131 | 132 | NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]; 133 | id objectValue = [self objectForColumnIndex:columnIdx]; 134 | [dict setObject:objectValue forKey:columnName]; 135 | } 136 | 137 | return dict; 138 | } 139 | else { 140 | NSLog(@"Warning: There seem to be no columns in this set."); 141 | } 142 | 143 | return nil; 144 | } 145 | 146 | 147 | 148 | 149 | - (BOOL)next { 150 | 151 | int rc = sqlite3_step([_statement statement]); 152 | 153 | if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { 154 | NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]); 155 | NSLog(@"Database busy"); 156 | } 157 | else if (SQLITE_DONE == rc || SQLITE_ROW == rc) { 158 | // all is well, let's return. 159 | } 160 | else if (SQLITE_ERROR == rc) { 161 | NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); 162 | } 163 | else if (SQLITE_MISUSE == rc) { 164 | // uh oh. 165 | NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); 166 | } 167 | else { 168 | // wtf? 169 | NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); 170 | } 171 | 172 | 173 | if (rc != SQLITE_ROW) { 174 | [self close]; 175 | } 176 | 177 | return (rc == SQLITE_ROW); 178 | } 179 | 180 | - (BOOL)hasAnotherRow { 181 | return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; 182 | } 183 | 184 | - (int)columnIndexForName:(NSString*)columnName { 185 | columnName = [columnName lowercaseString]; 186 | 187 | NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; 188 | 189 | if (n) { 190 | return [n intValue]; 191 | } 192 | 193 | NSLog(@"Warning: I could not find the column named '%@'.", columnName); 194 | 195 | return -1; 196 | } 197 | 198 | 199 | 200 | - (int)intForColumn:(NSString*)columnName { 201 | return [self intForColumnIndex:[self columnIndexForName:columnName]]; 202 | } 203 | 204 | - (int)intForColumnIndex:(int)columnIdx { 205 | return sqlite3_column_int([_statement statement], columnIdx); 206 | } 207 | 208 | - (long)longForColumn:(NSString*)columnName { 209 | return [self longForColumnIndex:[self columnIndexForName:columnName]]; 210 | } 211 | 212 | - (long)longForColumnIndex:(int)columnIdx { 213 | return (long)sqlite3_column_int64([_statement statement], columnIdx); 214 | } 215 | 216 | - (long long int)longLongIntForColumn:(NSString*)columnName { 217 | return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]]; 218 | } 219 | 220 | - (long long int)longLongIntForColumnIndex:(int)columnIdx { 221 | return sqlite3_column_int64([_statement statement], columnIdx); 222 | } 223 | 224 | - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName { 225 | return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]]; 226 | } 227 | 228 | - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx { 229 | return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx]; 230 | } 231 | 232 | - (BOOL)boolForColumn:(NSString*)columnName { 233 | return [self boolForColumnIndex:[self columnIndexForName:columnName]]; 234 | } 235 | 236 | - (BOOL)boolForColumnIndex:(int)columnIdx { 237 | return ([self intForColumnIndex:columnIdx] != 0); 238 | } 239 | 240 | - (double)doubleForColumn:(NSString*)columnName { 241 | return [self doubleForColumnIndex:[self columnIndexForName:columnName]]; 242 | } 243 | 244 | - (double)doubleForColumnIndex:(int)columnIdx { 245 | return sqlite3_column_double([_statement statement], columnIdx); 246 | } 247 | 248 | - (NSString*)stringForColumnIndex:(int)columnIdx { 249 | 250 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 251 | return nil; 252 | } 253 | 254 | const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); 255 | 256 | if (!c) { 257 | // null row. 258 | return nil; 259 | } 260 | 261 | return [NSString stringWithUTF8String:c]; 262 | } 263 | 264 | - (NSString*)stringForColumn:(NSString*)columnName { 265 | return [self stringForColumnIndex:[self columnIndexForName:columnName]]; 266 | } 267 | 268 | - (NSDate*)dateForColumn:(NSString*)columnName { 269 | return [self dateForColumnIndex:[self columnIndexForName:columnName]]; 270 | } 271 | 272 | - (NSDate*)dateForColumnIndex:(int)columnIdx { 273 | 274 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 275 | return nil; 276 | } 277 | 278 | return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]]; 279 | } 280 | 281 | 282 | - (NSData*)dataForColumn:(NSString*)columnName { 283 | return [self dataForColumnIndex:[self columnIndexForName:columnName]]; 284 | } 285 | 286 | - (NSData*)dataForColumnIndex:(int)columnIdx { 287 | 288 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 289 | return nil; 290 | } 291 | 292 | int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); 293 | 294 | NSMutableData *data = [NSMutableData dataWithLength:(NSUInteger)dataSize]; 295 | 296 | memcpy([data mutableBytes], sqlite3_column_blob([_statement statement], columnIdx), dataSize); 297 | 298 | return data; 299 | } 300 | 301 | 302 | - (NSData*)dataNoCopyForColumn:(NSString*)columnName { 303 | return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]]; 304 | } 305 | 306 | - (NSData*)dataNoCopyForColumnIndex:(int)columnIdx { 307 | 308 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 309 | return nil; 310 | } 311 | 312 | int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); 313 | 314 | NSData *data = [NSData dataWithBytesNoCopy:(void *)sqlite3_column_blob([_statement statement], columnIdx) length:(NSUInteger)dataSize freeWhenDone:NO]; 315 | 316 | return data; 317 | } 318 | 319 | 320 | - (BOOL)columnIndexIsNull:(int)columnIdx { 321 | return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL; 322 | } 323 | 324 | - (BOOL)columnIsNull:(NSString*)columnName { 325 | return [self columnIndexIsNull:[self columnIndexForName:columnName]]; 326 | } 327 | 328 | - (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx { 329 | 330 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 331 | return nil; 332 | } 333 | 334 | return sqlite3_column_text([_statement statement], columnIdx); 335 | } 336 | 337 | - (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { 338 | return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; 339 | } 340 | 341 | - (id)objectForColumnIndex:(int)columnIdx { 342 | int columnType = sqlite3_column_type([_statement statement], columnIdx); 343 | 344 | id returnValue = nil; 345 | 346 | if (columnType == SQLITE_INTEGER) { 347 | returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]]; 348 | } 349 | else if (columnType == SQLITE_FLOAT) { 350 | returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]]; 351 | } 352 | else if (columnType == SQLITE_BLOB) { 353 | returnValue = [self dataForColumnIndex:columnIdx]; 354 | } 355 | else { 356 | //default to a string for everything else 357 | returnValue = [self stringForColumnIndex:columnIdx]; 358 | } 359 | 360 | if (returnValue == nil) { 361 | returnValue = [NSNull null]; 362 | } 363 | 364 | return returnValue; 365 | } 366 | 367 | - (id)objectForColumnName:(NSString*)columnName { 368 | return [self objectForColumnIndex:[self columnIndexForName:columnName]]; 369 | } 370 | 371 | // returns autoreleased NSString containing the name of the column in the result set 372 | - (NSString*)columnNameForIndex:(int)columnIdx { 373 | return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)]; 374 | } 375 | 376 | - (void)setParentDB:(FMDatabase *)newDb { 377 | _parentDB = newDb; 378 | } 379 | 380 | - (id)objectAtIndexedSubscript:(int)columnIdx { 381 | return [self objectForColumnIndex:columnIdx]; 382 | } 383 | 384 | - (id)objectForKeyedSubscript:(NSString *)columnName { 385 | return [self objectForColumnName:columnName]; 386 | } 387 | 388 | 389 | @end 390 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // DBDemo 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/play.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/play.playground/section-1.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | //var str = "Hello, playground" 6 | 7 | print("Hello world!") -------------------------------------------------------------------------------- /DBDemo/DBDemo/play.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /DBDemo/DBDemo/resource/db.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/resource/db.sqlite -------------------------------------------------------------------------------- /DBDemo/DBDemo/resource/iphone-100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/resource/iphone-100.png -------------------------------------------------------------------------------- /DBDemo/DBDemo/resource/iphone-25.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/resource/iphone-25.png -------------------------------------------------------------------------------- /DBDemo/DBDemo/resource/iphone-25@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/resource/iphone-25@2x.png -------------------------------------------------------------------------------- /DBDemo/DBDemo/resource/iphone-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/DBDemo/DBDemo/resource/iphone-512.png -------------------------------------------------------------------------------- /DBDemo/DBDemoTests/DBDemoTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // DBDemoTests.m 3 | // DBDemoTests 4 | // 5 | // Created by Gerry on 14-9-21. 6 | // Copyright (c) 2014年 Gerry. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @interface DBDemoTests : XCTestCase 13 | 14 | @end 15 | 16 | @implementation DBDemoTests 17 | 18 | - (void)setUp { 19 | [super setUp]; 20 | // Put setup code here. This method is called before the invocation of each test method in the class. 21 | } 22 | 23 | - (void)tearDown { 24 | // Put teardown code here. This method is called after the invocation of each test method in the class. 25 | [super tearDown]; 26 | } 27 | 28 | - (void)testExample { 29 | // This is an example of a functional test case. 30 | XCTAssert(YES, @"Pass"); 31 | } 32 | 33 | - (void)testPerformanceExample { 34 | // This is an example of a performance test case. 35 | // [self measureBlock:^{ 36 | // // Put the code you want to measure the time of here. 37 | // }]; 38 | } 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /DBDemo/DBDemoTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | iDream.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /DBDemo/GXDatabaseUtils.podspec: -------------------------------------------------------------------------------- 1 | # 2 | # Be sure to run `pod spec lint GXDatabaseUtils.podspec' to ensure this is a 3 | # valid spec and to remove all comments including this before submitting the spec. 4 | # 5 | # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html 6 | # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ 7 | # 8 | 9 | Pod::Spec.new do |s| 10 | 11 | # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 12 | # 13 | # These will help people to find your library, and whilst it 14 | # can feel like a chore to fill in it's definitely to your advantage. The 15 | # summary should be tweet-length, and the description more in depth. 16 | # 17 | 18 | s.name = "GXDatabaseUtils" 19 | s.version = "1.0" 20 | s.summary = "simplify sqlite database CRUD operation." 21 | 22 | # This description is used to generate tags and improve search results. 23 | # * Think: What does it do? Why did you write it? What is the focus? 24 | # * Try to keep it short, snappy and to the point. 25 | # * Write the description between the DESC delimiters below. 26 | # * Finally, don't worry about the indent, CocoaPods strips it! 27 | s.description = <<-DESC 28 | simplify sqlite database CRUD operation. 29 | by gerry 30 | DESC 31 | 32 | s.homepage = "https://github.com/Gerry1218/GXDatabaseUtils" 33 | # s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" 34 | 35 | 36 | # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 37 | # 38 | # Licensing your code is important. See http://choosealicense.com for more info. 39 | # CocoaPods will detect a license file if there is a named LICENSE* 40 | # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. 41 | # 42 | 43 | s.license = "BSD" 44 | # s.license = { :type => "MIT", :file => "FILE_LICENSE" } 45 | 46 | 47 | # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 48 | # 49 | # Specify the authors of the library, with email addresses. Email addresses 50 | # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also 51 | # accepts just a name if you'd rather not provide an email address. 52 | # 53 | # Specify a social_media_url where others can refer to, for example a twitter 54 | # profile URL. 55 | # 56 | 57 | s.author = { "Gerry1218" => "gerry1218@163.com" } 58 | # Or just: s.author = "Gerry1218" 59 | # s.authors = { "Gerry1218" => "gerry1218@163.com" } 60 | # s.social_media_url = "http://twitter.com/xxx" 61 | 62 | # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 63 | # 64 | # If this Pod runs only on iOS or OS X, then specify the platform and 65 | # the deployment target. You can optionally include the target after the platform. 66 | # 67 | 68 | # s.platform = :ios 69 | # s.platform = :ios, "5.0" 70 | 71 | # When using multiple platforms 72 | # s.ios.deployment_target = "5.0" 73 | # s.osx.deployment_target = "10.7" 74 | # s.watchos.deployment_target = "2.0" 75 | # s.tvos.deployment_target = "9.0" 76 | 77 | 78 | # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 79 | # 80 | # Specify the location from where the source should be retrieved. 81 | # Supports git, hg, bzr, svn and HTTP. 82 | # 83 | 84 | s.source = { :git => "https://github.com/Gerry1218/GXDatabaseUtils.git", :tag => "#{s.version}" } 85 | 86 | 87 | # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 88 | # 89 | # CocoaPods is smart about how it includes source code. For source files 90 | # giving a folder will include any swift, h, m, mm, c & cpp files. 91 | # For header files it will include any header in the folder. 92 | # Not including the public_header_files will make all headers public. 93 | # 94 | 95 | s.source_files = 'DBDemo/Classes/*' 96 | #s.exclude_files = "Pod/Classes/Exclude" 97 | 98 | # s.public_header_files = "Classes/**/*.h" 99 | 100 | 101 | # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 102 | # 103 | # A list of resources included with the Pod. These are copied into the 104 | # target bundle with a build phase script. Anything else will be cleaned. 105 | # You can preserve files from being cleaned, please don't preserve 106 | # non-essential files like tests, examples and documentation. 107 | # 108 | 109 | # s.resource = "icon.png" 110 | # s.resources = "Resources/*.png" 111 | 112 | # s.preserve_paths = "FilesToSave", "MoreFilesToSave" 113 | 114 | 115 | # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 116 | # 117 | # Link your library with frameworks, or libraries. Libraries do not include 118 | # the lib prefix of their name. 119 | # 120 | 121 | # s.framework = "SomeFramework" 122 | # s.frameworks = "SomeFramework", "AnotherFramework" 123 | 124 | s.library = "sqlite3" 125 | # s.libraries = "iconv", "xml2" 126 | 127 | 128 | # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 129 | # 130 | # If your library depends on compiler flags you can set them in the xcconfig hash 131 | # where they will only apply to your library. If you depend on other Podspecs 132 | # you can include multiple dependencies to ensure it works. 133 | 134 | # s.requires_arc = true 135 | 136 | # s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } 137 | s.dependency "FMDB", '~> 2.6.2' 138 | 139 | end 140 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Gerry1218 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | GXDatabaseUtils 2 | =============== 3 | 4 | - simplify sqlite database CRUD operation. 5 | - Support ARC. 6 | - Support ios8 and before. 7 | 8 | ![Screen shot](docs/screen_shot.png) 9 | 10 | 11 | ## How To Get Started 12 | - Copy file under src and catagory directory to your project 13 | - [Download fmdb](https://github.com/ccgus/fmdb) relevant file 14 | - Add libsqlite3.dylib to project 15 | 16 | ## Support data types 17 | - BOOL 18 | - unsigned int 19 | - NSInteger 20 | - long long 21 | - CGFloat 22 | - double 23 | - NSString 24 | - BOOL for ios8 25 | - Enum for ios8 26 | 27 | ## Support iOS version 28 | iOS5 later 29 | 30 | ## Relationship class Member and column name 31 | `RULE:` column name is member name of class. 32 | 33 | For example: 34 | ```objective-c 35 | // class 36 | @interface GXBaseMessage : NSObject { 37 | 38 | NSString *address; 39 | } 40 | 41 | @property (nonatomic, assign) NSInteger count; 42 | @property (nonatomic, strong) NSString *name; 43 | @property (nonatomic, strong) NSMutableArray *datas; 44 | @end 45 | ``` 46 | 47 | | member name | column name | 48 | |:-------------:|:-----------:| 49 | | address | address | 50 | | count | _count| 51 | | name | _name| 52 | | datas | - | 53 | 54 | 55 | ## Dependencies 56 | - [fmdb](https://github.com/ccgus/fmdb) needed 57 | - NSObject subclass 58 | 59 | ## Architecture 60 | * `` 61 | - `NSObject+serializable` 62 | 63 | * `` 64 | - `GXDatabaseManager` 65 | - `GXSQLStatementManager` 66 | - `GXCache` 67 | 68 | ## Usage 69 | 70 | ### CRUD operation 71 | - `C-Create` 72 | - `R-Retrieve` 73 | - `U-Update` 74 | - `D-Delete` 75 | 76 | #### Create 77 | ```objective-c 78 | NSString *dbPath = [NSHomeDirectory() stringByAppendingPathComponent:@"testDB.sqlite"]; 79 | BOOL res = [GXDatabaseManager databaseWithPath:dbPath]; 80 | res = [GXDatabaseManager createTable:@"t_message" withClass:[GXMessage class] withPrimaryKey:@"_msgId"]; 81 | ``` 82 | 83 | #### Retrieve 84 | ```objective-c 85 | NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite"]; 86 | BOOL res = [GXDatabaseManager databaseWithPath:dbPath]; 87 | if (!res) { 88 | NSLog(@"ERROR..."); 89 | } 90 | 91 | NSString *w1 = kWhereString(@"_sessionUserid", @"="); 92 | NSString *w2 = kWhereString(@"_msgId", @"="); 93 | NSString *w = kWhereCombination(w1, @"AND", w2); 94 | 95 | [GXDatabaseManager selectObjects:[GXMessageDBEntity class] 96 | fromTable:@"t_message_chat" 97 | where:w 98 | withParams:@[@"1525851662", @"615734ef-2db1-427a-9505-b49ec6a8628c"] 99 | orderBy:@"_msgTime" 100 | withSortType:@"DESC" 101 | withRange:NSMakeRange(0, 5)]; 102 | ``` 103 | 104 | #### Update 105 | ```objective-c 106 | // replace into 107 | NSString *dbPath = [NSHomeDirectory() stringByAppendingPathComponent:@"testDB.sqlite"]; 108 | BOOL res = [GXDatabaseManager databaseWithPath:dbPath]; 109 | 110 | // create table 111 | res = [GXDatabaseManager createTable:@"t_message" withClass:[GXMessage class] withPrimaryKey:@"_msgId"]; 112 | 113 | [GXDatabaseManager replaceInto:@"t_message" withObject:msg]; 114 | ``` 115 | ```objective-c 116 | // update 117 | NSString *dbPath = [NSHomeDirectory() stringByAppendingPathComponent:@"testDB.sqlite"]; 118 | BOOL res = [GXDatabaseManager databaseWithPath:dbPath]; 119 | 120 | if (!res) NSLog(@"ERROR"); 121 | 122 | 123 | NSString *w = kWhereString(@"_msgId", @"="); 124 | [GXDatabaseManager updateTable:@"t_message" 125 | set:@[@"_fontName"] 126 | where:w 127 | withParams:@[@"黑体", @"1ccaf308-8bb0-1e44-2f0b-98f308d03d57"]]; 128 | ``` 129 | 130 | #### Delete 131 | ```objective-c 132 | NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite"]; 133 | BOOL res = [GXDatabaseManager databaseWithPath:dbPath]; 134 | if (!res) NSLog(@"ERROR..."); 135 | 136 | [GXDatabaseManager deleteTable:@"t_message_chat" where:@"_msgId=?" withParams:@[@"1ccaf308-8bb0-1e44-2f0b-98f308d03d57"]]; 137 | ``` 138 | 139 | --- 140 | 141 | ## License 142 | 143 | GXDatabaseUtils is available under the MIT license. See the LICENSE file for more info. 144 | 145 | -------------------------------------------------------------------------------- /docs/screen_shot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gerry1218/GXDatabaseUtils/5f5554a769b8d5a7dcef538e552aa027972578e8/docs/screen_shot.png -------------------------------------------------------------------------------- /testDB.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /testDB.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | --------------------------------------------------------------------------------