#import "ZYDataManager.h" #import "JSSportModel.h" FMDatabase *db = nil; @implementation ZYDataManager +(NSString *)dbFilePath { return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/data.sqlite"]; } +(FMDatabase *)getDataBase { //第一次打开数据库时,db对象不存在,需要创建 if (db == nil) { db = [FMDatabase databaseWithPath:[self dbFilePath]]; } return db; } // +(void)createTable { NSLog(@"%@",NSHomeDirectory()); if (![db open]) { NSAssert(NO, @"数据库打开失败"); } //设置是否缓存数据 [db setShouldCacheStatements:YES]; //判断表是否存在 if (![db tableExists:@"people"]) { if (![db executeUpdate:@"create table if not exists sportTable(id INTEGER PRIMARY KEY, date TEXT, sportArray TEXT);"]) { NSLog(@"数据表创建失败"); } } } // +(void)addNewJSSport:(JSSportModel *)JSModel { if (![db open]) { NSAssert(NO, @"数据库打开失败"); } if (![db tableExists:@"people"]) { [self createTable]; } //?对应的字段值必须是(OC中字符串) if (![db executeUpdate:@"insert into sportTable (date, sportArray) values (?,?)", JSModel.dateStr,JSModel.arrayStr]) { NSLog(@"插入数据失败"); } [db close]; } +(NSMutableArray *)getAllFriend { if (![db open]) { NSAssert(NO, @"数据库打开失败"); } if (![db tableExists:@"sportTable"]) { return nil; } NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0]; FMResultSet *rs = [db executeQuery:@"select * from sportTable;"]; //遍历所有满足条件的好友记录 while([rs next]) { JSSportModel *jssportModel = [[JSSportModel alloc] init]; // jssportModel.rowId = [rs intForColumn:@"id"]; jssportModel.dateStr = [rs stringForColumn:@"date"]; jssportModel.arrayStr = [rs stringForColumn:@"sportArray"]; //保存好友记录 [array addObject:jssportModel]; } [rs close]; [db close]; return array ; } // //+(void)deleteOneFriend:(Friend *)aFriend //{ // if (![db open]) { // NSAssert(NO, @"数据库打开失败"); // } // // if (![db tableExists:@"people"]) { // NSLog(@"数据表不存在,不要删除"); // } // // if([db executeUpdate:@"delete from people where id = ?", [NSNumber numberWithInt:aFriend.rowId]]) // { // NSLog(@"id = %d的记录删除成功!", aFriend.rowId); // } // [db close]; //} @end
#import <Foundation/Foundation.h> //#import "FMDatabase.h" //#import "FMDatabaseAdditions.h" //#import "Friend.h" @class JSSportModel; @interface ZYDataManager : NSObject +(NSString *)dbFilePath; +(FMDatabase *)getDataBase; +(void)createTable; +(void)addNewJSSport:(JSSportModel *)JSModel; +(NSMutableArray *)getAllFriend; //+(void)deleteOneFriend:(Friend *)aFriend; @end