使用LKDBHelper操作數(shù)據(jù)庫

LKDBHelper以實體類對象進行數(shù)據(jù)庫的操作,例如新建一個新聞實體類,以這個類來操作新聞相關(guān)的數(shù)據(jù),類名為:StockNewsEntity;

1、//獲取新聞數(shù)據(jù)庫地址

+ (LKDBHelper *)getStockNewsLKDBHelper {

static LKDBHelper* db;

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

NSString* dbpath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/StockNews.db"];

db = [[LKDBHelper alloc]initWithDBPath:dbpath];

});

return db;

}

2、插入新聞數(shù)據(jù)庫

+ (void)insertToStockNewsDB:(StockNewsEntity *)model {

LKDBHelper* globalHelper = [StockNewsEntity getStockNewsLKDBHelper];

//保存到數(shù)據(jù)庫

[globalHelper insertToDB:model];

}

3、查詢新聞數(shù)據(jù)庫

+ (NSMutableArray *)selectStockNewsWithWhere:(id)where orderBy:(NSString *)orderBy {

LKDBHelper* globalHelper = [StockNewsEntity getStockNewsLKDBHelper];

NSMutableArray *array = [globalHelper search:[StockNewsEntity class] where:where orderBy:orderBy offset:0 count:0];

return array;

}

4、更新數(shù)據(jù)庫,返回值bool類型

+ (BOOL)upDateToHistoryDBSet:(NSString *)set where:(id)where{

LKDBHelper* globalHelper = [StockEntity getSearchHistoryLKDBHelper];

//更新數(shù)據(jù)庫

BOOL isUpdate = [globalHelper updateToDB:[StockEntity class] set:set where:where];

return isUpdate;

}

5、刪除數(shù)據(jù)庫(可以刪除表,也可以刪除某一條具體的數(shù)據(jù))

[globalHelper deleteWithClass:[StockEntity class] where:@{@"mkt":USA}];//從表中刪除mkt是USA的數(shù)據(jù)條

[globalHelper deleteWithClass:[StockEntity class] where:nil];//刪除表

6、如果數(shù)據(jù)庫中插入大量的數(shù)據(jù)是一個很耗時的操作,此時如果用數(shù)據(jù)庫的事務(wù)來進行數(shù)據(jù)庫的操作,會節(jié)省大量的時間,下面是一段基于LKDBHelper的事務(wù)插入數(shù)據(jù)庫操作

- (void)insertToDBWithDB:(LKDBHelper *)globalHelper dataArray:(NSArray *)tempArray {

[globalHelper executeDB:^(FMDatabase *db) {

@try {

[db beginTransaction];

for (int i = 0; i<tempArrary.count;i++){

StockEntity *model = [StockEntity dictionEntity:tempArray[i]];

if (judgeNULL(model.cname)) {

model.cname = model.name;

//保存到數(shù)據(jù)庫

[globalHelper insertToDB:model];

} @catch (NSException *exception) {

[db rollback];

}@finally{

[db commit];

}

}];

主要由@try{

[db beginTransaction];

}@catch(NSException *exception){

[db rollback];

}@finally{

[db commit];

}

[關(guān)于事務(wù)可查看](http://blog.csdn.net/x32sky/article/details/45531229)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容