前言:
在項目中會經(jīng)常遇到數(shù)據(jù)寫入本地,讀取等等操作,這樣的操作會經(jīng)常用到,所以就封裝了一個類方法
前提:
是要用cocoapods下載FMDB
框架,我用到是模型來存儲數(shù)據(jù)的,大家也可以用字典來存儲,一樣的道理,封裝類方法如下:
- .h文件如下:
#import <Foundation/Foundation.h>
#import "FMDB.h"
@class TestModel;
@class DetectModel;
@interface FmdbTooler : NSObject
+(FmdbTooler*)sharedInstance;
- (void)openDatabaseWithUserName:(NSString*)userName;
// 往數(shù)據(jù)庫寫入數(shù)據(jù)ut_detect add by bob
-(BOOL)addUt_detectLogsave:(DetectModel *)model;
// 獲取ut_detect表下面的數(shù)據(jù) add by bob
- (NSMutableArray *)getUt_detectDataDetial;
// 根據(jù)detectingdate刪除某個咨詢對話 add by bob
-(BOOL)deleteUt_detectOfVisitid:(NSString *)detectingdate;
//更新detectingdate對應的咨詢對話信息UPDATE 表名稱 SET 列名稱 = 新值 WHERE 列名稱 = 某值
- (void)updateUt_detectOfVisitid:(NSString *)detectingdate logsave:(DetectModel *)model;
// 根據(jù)detectingdate判斷數(shù)據(jù)是否存在
-(BOOL)isExitUt_detectOfDetectingdate:(NSString *)detectingdate;
// ut_testing表
// 往數(shù)據(jù)庫寫入數(shù)據(jù) add by bob
-(BOOL)addUt_testingLogsave:(TestModel *)model;
// 獲取ut_testing表下面的數(shù)據(jù) add by bob
- (NSMutableArray *)getUt_testingDataDetial;
// 根據(jù)testingid刪除某個咨詢對話 add by bob
-(BOOL)deleteUt_testingOfVisitid:(NSInteger)testingid;
@end
- .m實現(xiàn)方法:
#import "FmdbTooler.h"
#import <CommonCrypto/CommonDigest.h>
#import "DetectModel.h"
#import "TestModel.h"
@interface FmdbTooler()
@property (nonatomic, strong) FMDatabase *dataBase;
@end
@implementation FmdbTooler
+(FmdbTooler*)sharedInstance{
static FmdbTooler* dbmanager;
static dispatch_once_t dbmanageronce;
dispatch_once(&dbmanageronce, ^{
dbmanager = [[FmdbTooler alloc] init];
});
return dbmanager;
}
- (void)openDatabaseWithUserName:(NSString*)userName {
if (userName.length==0) {
return;
}
//Documents:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//username md5
const char *cStr = [userName UTF8String];
unsigned char result[16];
CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
NSString* MD5 = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],result[8], result[9], result[10], result[11],result[12], result[13], result[14], result[15]];
//數(shù)據(jù)庫文件夾
NSString * documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:MD5];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir = FALSE;
BOOL isDirExist = [fileManager fileExistsAtPath:documentsDirectory isDirectory:&isDir];
if(!(isDirExist && isDir)) {
BOOL bCreateDir = [fileManager createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:nil];
if(!bCreateDir) {
NSLog(@"Create Database Directory Failed.");
}
NSLog(@"%@", documentsDirectory);
}
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"ut_database.db"];
if (self.dataBase) {
[self.dataBase close];
self.dataBase = nil;
}
self.dataBase = [FMDatabase databaseWithPath:dbPath];
[self.dataBase open];
// 新建ut_detect數(shù)據(jù)表
[self ut_detectTableCreate];
// 新建ut_testing數(shù)據(jù)表
[self ut_testingTableCreate];
}
// 判斷指定表是否存在
- (BOOL)checkTableExist:(NSString *)tableName {
BOOL result = NO;
NSString* lowtableName = [tableName lowercaseString];
FMResultSet *rs = [self.dataBase executeQuery:@"SELECT [sql] FROM sqlite_master WHERE [type] = 'table' AND lower(name) = ?", lowtableName];
result = [rs next];
[rs close];
return result;
}
// 創(chuàng)建表
- (void) createTable:(NSString*)tableName sql:(NSString *)createSql {
BOOL isExist = [self.dataBase tableExists:tableName];
if (!isExist) {
[self.dataBase executeUpdate:createSql];
}
}
- (BOOL)runSql:(NSString*)sql {
return [self.dataBase executeUpdate:sql];
}
- (int)getCountWithSql:(NSString*)sql {
int count = 0;
FMResultSet *rs = [self.dataBase executeQuery:sql];
if ([rs next]) {
count = [rs intForColumnIndex:0];
}
[rs close];
return count;
}
// 創(chuàng)建 ut_detect 表
- (void)ut_detectTableCreate{
[self createTable:@"ut_detect" sql:@"CREATE table ut_detect (detectingdate varchar(64) PRIMARY KEY, deviceid varchar(64), indexuom varchar(64),pvalue varchar(64),frequency varchar(64),minvalue varchar(64),maxvalue varchar(64))"];
}
// 往數(shù)據(jù)庫寫入數(shù)據(jù) add by bob
-(BOOL)addUt_detectLogsave:(DetectModel *)model {
//增加一條記錄
return [self.dataBase executeUpdate:@"INSERT INTO ut_detect(detectingdate, deviceid, indexuom, pvalue, frequency, minvalue, maxvalue) VALUES (?,?,?,?,?,?,?)", model.detectingdate, model.detectid, model.indexuom, model.pvalue, model.frequency, model.minvalue, model.maxvalue];
}
// 獲取ut_detect表下面的數(shù)據(jù) add by bob
- (NSMutableArray *)getUt_detectDataDetial{
NSMutableArray *detectArray = [NSMutableArray array];
FMResultSet *rs = [self.dataBase executeQuery:[NSString stringWithFormat:@"SELECT * FROM ut_detect"]];
while ([rs next]){ // 這些屬性名務必按創(chuàng)建表時候的順序來寫
DetectModel *model = [[DetectModel alloc] init];
int columnIndex = 0;
model.detectingdate = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.deviceid = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.indexuom = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.pvalue = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.frequency = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.minvalue = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.maxvalue = [rs stringForColumnIndex:columnIndex]; columnIndex++;
[detectArray addObject:model];
}
[rs close];
return detectArray;
}
// 根據(jù)detectingdate刪除某個咨詢對話 add by bob
-(BOOL)deleteUt_detectOfVisitid:(NSString *)detectingdate {
return [self runSql:[NSString stringWithFormat:@"DELETE FROM ut_detect WHERE detectingdate = %@",detectingdate]];
}
//更新detectingdate對應的咨詢對話信息UPDATE 表名稱 SET 列名稱 = 新值 WHERE 列名稱 = 某值
- (void)updateUt_detectOfVisitid:(NSString *)detectingdate logsave:(DetectModel *)model {
[self runSql:[NSString stringWithFormat:@"UPDATE ut_detect SET indexuom = '%@', pvalue = '%@', frequency = '%@', minvalue = '%@', maxvalue = '%@' WHERE detectingdate = '%@'",model.indexuom, model.pvalue, model.frequency, model.minvalue, model.maxvalue, detectingdate]];
}
// 根據(jù)detectingdate判斷數(shù)據(jù)是否存在
-(BOOL)isExitUt_detectOfDetectingdate:(NSString *)detectingdate {
int count = [self getCountWithSql:[NSString stringWithFormat:@"SELECT count(*) FROM ut_detect WHERE detectingdate = '%@'", detectingdate]];
if (count > 0) {
return YES;
}else{
return NO;
}
}
// 創(chuàng)建 ut_testing 表
- (void)ut_testingTableCreate{
[self createTable:@"ut_testing" sql:@"CREATE table ut_testing (testingid INTEGER PRIMARY KEY AUTOINCREMENT, deviceid varchar(64), testtype varchar(64), testtime varchar(64),indexuom varchar(64),pvalue varchar(64),frequency varchar(64),minvalue varchar(64),maxvalue varchar(64),strength varchar(64),fatigue varchar(64), dectecttime varvhar(5000))"];
}
// 往數(shù)據(jù)庫寫入數(shù)據(jù) add by bob
-(BOOL)addUt_testingLogsave:(TestModel *)model {
//增加一條記錄
return [self.dataBase executeUpdate:@"INSERT INTO ut_testing(deviceid, testtype, testtime, indexuom, pvalue, frequency, minvalue, maxvalue, strength, fatigue, dectecttime) VALUES (?,?,?,?,?,?,?,?,?,?,?)", model.deviceid, model.testtype, model.testtime, model.indexuom, model.pvalue, model.frequency, model.minvalue, model.maxvalue, model.strength, model.fatigue, model.dectecttime];
}
// 獲取ut_detect表下面的數(shù)據(jù) add by bob
- (NSMutableArray *)getUt_testingDataDetial{
NSMutableArray *detectArray = [NSMutableArray array];
FMResultSet *rs = [self.dataBase executeQuery:[NSString stringWithFormat:@"SELECT * FROM ut_testing"]];
while ([rs next]){
TestModel *model = [[TestModel alloc] init];
int columnIndex = 0; // 這些屬性名務必按創(chuàng)建表時候的順序來寫
model.testingid = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.deviceid = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.testtype = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.testtime = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.indexuom = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.pvalue = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.frequency = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.minvalue = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.maxvalue = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.strength = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.fatigue = [rs stringForColumnIndex:columnIndex]; columnIndex++;
model.dectecttime = [rs stringForColumnIndex:columnIndex]; columnIndex++;
[detectArray addObject:model];
}
[rs close];
return detectArray;
}
// 根據(jù)detectingdate刪除某個咨詢對話 add by bob
-(BOOL)deleteUt_testingOfVisitid:(NSInteger)testingid {
return [self runSql:[NSString stringWithFormat:@"DELETE FROM ut_testing WHERE testingid = %ld",(long)testingid]];
}
具體用法如下:
首先是導入頭文件
NSString *uid = [WSUserUtil getUser]._id;
// 打開數(shù)據(jù)庫
[[FmdbTooler sharedInstance] openDatabaseWithUserName:uid];
// 檢測數(shù)據(jù)是否存在 currentDate 查詢的條件
[[FmdbTooler sharedInstance] isExitUt_detectOfDetectingdate:currentDate]
//添加
[[FmdbTooler sharedInstance] addUt_detectLogsave:model];
// 讀取表內(nèi)的所有數(shù)據(jù) , 從數(shù)據(jù)庫中讀取
NSArray *detectData = [[FmdbTooler sharedInstance] getUt_detectDataDetial];
// 根據(jù)某個屬性刪除某個數(shù)據(jù)
[[FmdbTooler sharedInstance] deleteUt_detectOfVisitid:currentDate]
應部分人的要求,把上文中所有用到的 model 開放出來;
- DetectModel
#import <Foundation/Foundation.h>
@interface DetectModel : NSObject
// 檢測數(shù)據(jù)標識
@property (copy, nonatomic) NSString *detectid;
// 設備標識
@property (copy, nonatomic) NSString *deviceid;
// 采樣日期
@property (copy, nonatomic) NSString *detectingdate;
// 單位
@property (copy, nonatomic) NSString *indexuom;
// 校準值
@property (copy, nonatomic) NSString *pvalue;
// 采樣周期
@property (copy, nonatomic) NSString *frequency;
// 最大值
@property (copy, nonatomic) NSString *minvalue;
// 最小值
@property (copy, nonatomic) NSString *maxvalue;
@end
- TestModel
#import <Foundation/Foundation.h>
@interface TestModel : NSObject
// 測試采樣標識
@property (copy, nonatomic) NSString *testingid;
// 檢測類型
@property (copy, nonatomic) NSString *deviceid;
// 檢測類型
@property (copy, nonatomic) NSString *testtype;
// 測試日期
@property (copy, nonatomic) NSString *testtime;
// 單位
@property (copy, nonatomic) NSString *indexuom;
// 校準值
@property (copy, nonatomic) NSString *pvalue;
// 采樣周期
@property (copy, nonatomic) NSString *frequency;
// 最大值
@property (copy, nonatomic) NSString *minvalue;
// 最小值
@property (copy, nonatomic) NSString *maxvalue;
// 肌力
@property (copy, nonatomic) NSString *strength;
// 疲勞度
@property (copy, nonatomic) NSString *fatigue;
// 采樣時間點
@property (copy, nonatomic) NSString *dectecttime;
@end