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)