該類繼承自 NSObject
本部分內(nèi)容放在專門的DataBase.m文件
#import "DataBase.h"
@implementation DataBase
static sqlite3 * db = nil;
+(sqlite3 *)openDB
{
//判斷當前數(shù)據(jù)庫是否存在,如果存在直接返回谜疤,否則進行數(shù)據(jù)庫創(chuàng)建
if (db) {
return db;
}
//創(chuàng)建數(shù)據(jù)庫
//獲取當前數(shù)據(jù)庫文件路徑
NSString * dataBasePath = [[NSBundle mainBundle] pathForResource:@"cart" ofType:@"sqlite"];
//獲取APP沙盒路徑
NSString * searchPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
searchPath = [searchPath stringByAppendingPathComponent:@"cart.sqlite"];//名字一般一樣,看著舒服
//判斷沙盒中是否存在該數(shù)據(jù)庫
if (![[NSFileManager defaultManager] fileExistsAtPath:searchPath]) {
//將數(shù)據(jù)庫移動至沙盒當中
[[NSFileManager defaultManager] copyItemAtPath:dataBasePath toPath:searchPath error:nil];
}
//打開指定位置的數(shù)據(jù)庫
sqlite3_open([searchPath UTF8String], &db);
return db;
}
+(void)closeDB
{
sqlite3_close(db);
}
@end