LKDBHelper以实体类对象进行数据库的操作,例如新建一个新闻实体类,以这个类来操作新闻相关的数据,类名为:StockNewsEntity;
1、//获取新闻数据库地址
+ (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、插入新闻数据库
+ (void)insertToStockNewsDB:(StockNewsEntity *)model {
LKDBHelper* globalHelper = [StockNewsEntity getStockNewsLKDBHelper];
//保存到数据库
[globalHelper insertToDB:model];
}
3、查询新闻数据库
+ (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、更新数据库,返回值bool类型
+ (BOOL)upDateToHistoryDBSet:(NSString *)set where:(id)where{
LKDBHelper* globalHelper = [StockEntity getSearchHistoryLKDBHelper];
//更新数据库
BOOL isUpdate = [globalHelper updateToDB:[StockEntity class] set:set where:where];
return isUpdate;
}
5、删除数据库(可以删除表,也可以删除某一条具体的数据)
[globalHelper deleteWithClass:[StockEntity class] where:@{@"mkt":USA}];//从表中删除mkt是USA的数据条
[globalHelper deleteWithClass:[StockEntity class] where:nil];//删除表
6、如果数据库中插入大量的数据是一个很耗时的操作,此时如果用数据库的事务来进行数据库的操作,会节省大量的时间,下面是一段基于LKDBHelper的事务插入数据库操作
- (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;
//保存到数据库
[globalHelper insertToDB:model];
} @catch (NSException *exception) {
[db rollback];
}@finally{
[db commit];
}
}];
主要由@try{
[db beginTransaction];
}@catch(NSException *exception){
[db rollback];
}@finally{
[db commit];
}
[关于事务可查看](http://blog.csdn.net/x32sky/article/details/45531229)