記錄下
單例的宏使用,是爲了簡化及統一,使用,參考前一篇文章或是去網上找相關的代碼。
部分代碼參考自互聯網,主要是加了pthread_mutex_t, 保證線程安全, 在openDb, closeDb中lock, unlock保證安全,因此在操作數據庫時,保證調用openDb, closeDb,成對使用,不要去考慮在主線程,還是其它線程中使用數據庫了。
只是提供一個框架和示例,具體應用根據自己的需要去添加。
頭文件
#import <Foundation/Foundation.h>
#include "SingletonMacro.h"
@interface VRSQLite : NSObject
HFSingletonH(VRSQLite)
@end
實現文件
#import "VRSQLite.h"
#import <sqlite3.h>
#include <pthread.h>
@interface VRSQLite ()
{
//數據指針,通過指針可以操作對應的數據庫
sqlite3 *dbPoint ;
pthread_mutex_t mutex;
}
@end
@implementation VRSQLite
HFSingletonM(VRSQLite)
-(instancetype) init{
self = [super init];
if(self){
[self setup];
}
return self;
}
- (void) setup{
pthread_mutex_init(&mutex, NULL);
[self createTable];
}
//打開數據庫
-(void)openDb{
pthread_mutex_lock(&mutex);
//想要打開的數據可路徑
NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"vr.db"];
NSLog(@"%@",dbPath);
/*
參數1:想要打開的數據庫的路徑,需要的是C語言的字符串
參數2:將dbPoint 指針和數據庫綁定,通過dbPoint可以訪問該路徑下的數據庫
如果該路徑下不存在對應的數據庫,系統會自動創建一個數據庫
*/
int result = sqlite3_open(dbPath.UTF8String, &dbPoint);
if (SQLITE_OK == result ) {
NSLog(@"數據庫打開成功");
}
else
{
NSLog(@"數據庫打開失敗");
}
}
//關閉數據庫
-(void)closeDb{
int result = sqlite3_close(dbPoint) ;
[self judgeWithResult:result action:@"關閉數據庫"];
pthread_mutex_unlock(&mutex);
}
-(void)judgeWithResult:(int)result action:(NSString *)actionStr{
if (result == SQLITE_OK) {
NSLog(@"%@成功",actionStr);
}
else
{
NSLog(@"%@失敗",actionStr);
}
}
//創建表
-(void)createTable{
[self openDb];
NSString *sqlStr = @"create table vritem (localIdentifier text , media_id text )";
/**
* 參數1:要使用的是哪一個數據庫
* 參數2:想對數據做什麼操作 SQL語句
* 參數3/4:系統預留的參數
* 參數5:錯誤信息
*
* @return return value description
*/
char **error ;
int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
NSLog(@"%s",error);
[self judgeWithResult:result action:@"創建表"];
//銷燬指針
sqlite3_free(error) ;
[self closeDb];
}
//添加
-(void)insertItem:(PTCloudSqlModel *)stu{
[self openDb];
NSString *sqlStr = [NSString stringWithFormat:@"insert into vritem values ('%@','%@')",stu.localIdentifier,stu.media_id];
char**error ;
int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
[self judgeWithResult:result action:@"插入"];
sqlite3_free(error);
[self closeDb];
}
//刪除記錄
-(void)deleteItem:(PTCloudSqlModel *)stu{
[self openDb];
NSString *sqlStr = [NSString stringWithFormat:@"delete from vritem where localIdentifier = \'%@' ",stu.localIdentifier];
char **error ;
int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
[self judgeWithResult:result action:@"刪除"];
sqlite3_free(error);
[self closeDb];
}
@end