數(shù)據(jù)庫在開發(fā)過程是常用到的數(shù)據(jù)處理工具仰挣,在以后的開發(fā)過程中也會常常用到佑颇,下面我來淺談一下框架 FMDB的封裝使用方案奸绷。
首先刃唐,我們來封裝一個FMDB的BaseManager管理者,在.h文件里添加一個數(shù)據(jù)庫操作對象屬性:@property (nonatomic, readonly) FMDatabase *dataBase以及你數(shù)據(jù)庫地址的一個屬性;
創(chuàng)建一個管理單例對象:+(YJDataBaseManager *)defaultDBManager;
創(chuàng)建一個連接數(shù)據(jù)庫方法:- (void)connect;
關(guān)閉數(shù)據(jù)庫的方法:- (void)close减宣;
在你的.m文件實現(xiàn)方法:首先初始化數(shù)據(jù)庫管理者:+ (YJDataBaseManager *)defaultDBManager {
if (!sharedDBManager) {
sharedDBManager = [[YJDataBaseManager alloc] init];
}
return sharedDBManager;
}
- (id)init {
self = [super init];
if (self) {
int state = [self initializeDBWithName:kDefaultDBName];
if (state == -1) {
NSLog(@"數(shù)據(jù)庫初始化失敗");
} else {
NSLog(@"??數(shù)據(jù)庫初始化成功");
}
}
return self;
}- (id)init {
self = [super init];
if (self) {
int state = [self initializeDBWithName:kDefaultDBName];
if (state == -1) {
NSLog(@"數(shù)據(jù)庫初始化失敗");
} else {
NSLog(@"??數(shù)據(jù)庫初始化成功");
}
}
return self;
}
返回數(shù)據(jù)庫初始化狀態(tài)(0 為 已經(jīng)存在狠角,1 為創(chuàng)建成功,-1 為創(chuàng)建失旘揭浮)
- (int)initializeDBWithName:(NSString *)nameStr
{
if (!nameStr) {
return -1;? // 返回數(shù)據(jù)庫創(chuàng)建失敗
}
// 沙盒Docu目錄
NSString * docp = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
name = [docp stringByAppendingString:[NSString stringWithFormat:@"/%@",nameStr]];
NSLog(@"數(shù)據(jù)庫地址-----------%@",name);
NSFileManager * fileManager = [NSFileManager defaultManager];
BOOL exist = [fileManager fileExistsAtPath:name];
[self connect];
if (!exist) {
return 0;
} else {
return 1; ? ? ? ? ?
}
}
連接數(shù)據(jù)庫
- (void)connect
{
if (!_dataBase) {
//根據(jù)文件路徑來創(chuàng)建FMDatabase對象
_dataBase = [[FMDatabase alloc] initWithPath:name];
}
if (![_dataBase open]) {
NSLog(@"不能打開數(shù)據(jù)庫");
}
}
關(guān)閉連接
- (void)close
{
[_dataBase close];
sharedDBManager = nil;
}
到這里已經(jīng)結(jié)束了FMDB管理者的定義封裝丰歌,接下來我們創(chuàng)建一個用戶數(shù)據(jù)處理的端口,主要用來進行數(shù)據(jù)的模糊查找屉凯、數(shù)據(jù)添加立帖、數(shù)據(jù)刪除、數(shù)據(jù)修改的方法悠砚。首先在.h文件添加如下方法:
user 需要保存的用戶數(shù)據(jù):- (void)saveUser:(YJUserModel *)userModel;
uid 需要刪除的用戶的id:- (void)deleteUserInfoWithId:(NSString *)uid;
需要修改的用戶信息:- (void)mergeWithUser:(YJUserModel *)userModel;
模擬分頁查找數(shù)據(jù):-(NSArray *)findWithUid:(NSString *)uid limit:(int)limit;
標識是否是全稱查詢or模糊查詢? YES(單個查詢) ? NO (模糊查詢):- (NSArray *)selectWithName:(NSString *)name Bools:(BOOL)bools;
刪除數(shù)據(jù)庫文件:- (void)deleteUserInfoWithDB;
創(chuàng)建數(shù)據(jù)庫:- (void)createDataBase;
在.m文件實現(xiàn)以上方法
- (id)init
{
self = [super init];
if (self) {
db = [YJDataBaseManager defaultDBManager].dataBase;
}
return self;
}
- (void)createDataBase
{
FMResultSet *resultSet = [db executeQuery:[NSString stringWithFormat:@"select count(*) from sqlite_master where type ='table' and name = '%@'",kUserName]];
[resultSet next];
NSInteger count = [resultSet intForColumnIndex:0];
BOOL exist = !!count;
if (exist) {
//TODO:數(shù)據(jù)庫已存在
NSLog(@"數(shù)據(jù)庫已存在");
}else{//TODO: 插入新的數(shù)據(jù)庫數(shù)據(jù)
NSString *sql = @"CREATE TABLE userName (uid INTEGER PRIMARY KEY AUTOINCREMENT? NOT NULL, imgstr VARCHAR(50), name VARCHAR(100), descrite VARCHAR(150))";
BOOL res = [db executeUpdate:sql];
if (!res) {
NSLog(@"數(shù)據(jù)庫創(chuàng)建失敗");
}else{
NSLog(@"數(shù)據(jù)庫創(chuàng)建成功");
}
}
}
/**
* @brief 保存一條用戶記錄
*
* @param userModel 需要保存的用戶數(shù)據(jù)
*/
- (void)saveUser:(YJUserModel *)userModel
{
NSMutableString *query = [NSMutableString stringWithFormat:@"INSERT INTO userName"];
NSMutableString *keys = [NSMutableString stringWithFormat:@" ("];
NSMutableString *values = [NSMutableString stringWithFormat:@" ( "];
NSMutableArray? *arguments = [NSMutableArray arrayWithCapacity:5];
if (userModel.imgstr) {
[keys appendString:@"imgstr,"];
[values appendString:@"?,"];
NSData *dataSTR = [NSData dataWithBase64EncodedString:userModel.imgstr];
NSString *str = [dataSTR base64EncodedString];
[arguments addObject:str];
}
if (userModel.name) {
[keys appendString:@"name,"];
[values appendString:@"?,"];
[arguments addObject:userModel.name];
}
if (userModel.descrite) {
[keys appendString:@"descrite,"];
[values appendString:@"?,"];
[arguments addObject:userModel.descrite];
}
[keys appendString:@")"];
[values appendString:@")"];
[query appendFormat:@" %@ VALUES%@",
[keys stringByReplacingOccurrencesOfString:@",)" withString:@")"],
[values stringByReplacingOccurrencesOfString:@",)" withString:@")"]];
if ([db executeUpdate:query withArgumentsInArray:arguments]) {
NSLog(@"插入一條數(shù)據(jù)");
}
}
/**
* @brief 刪除一條用戶數(shù)據(jù)
*
* @param uid 需要刪除的用戶的id
*/
- (void)deleteUserInfoWithId:(NSString *)uid
{
NSString *query = [NSString stringWithFormat:@"DELETE FROM userName WHERE uid = '%@'",uid];
if ([db executeUpdate:query]) {
NSLog(@"刪除一條數(shù)據(jù)");
}
}
/**
* @brief 修改用戶的信息
*
* @param userModel 需要修改的用戶信息
*/
- (void)mergeWithUser:(YJUserModel *)userModel
{
if (!userModel.uid) {
return;
}
NSString *query = @"UPDATE userName SET";
NSMutableString *temp = [NSMutableString stringWithCapacity:20];
if (userModel.imgstr) {
[temp appendFormat:@" imgstr = '%@',",userModel.imgstr];
}
if (userModel.name) {
[temp appendFormat:@" name = '%@',",userModel.name];
}
if (userModel.descrite) {
[temp appendFormat:@" descrite = '%@',",userModel.descrite];
}
[temp appendString:@")"];
query = [query stringByAppendingFormat:@"%@ WHERE uid = '%@'",[temp stringByReplacingOccurrencesOfString:@",)" withString:@""],userModel.uid];
if ([db executeUpdate:query]) {
NSLog(@"修改數(shù)據(jù)/成功");
}else{
NSLog(@"修改數(shù)據(jù)/失敗");
}
}
/**
* @brief 模擬分頁查找數(shù)據(jù)晓勇。取uid大于某個值以后的limit個數(shù)據(jù)
*
* @param uid
* @param limit 每頁取多少個
*/
- (NSArray *)findWithUid:(NSString *)uid limit:(int)limit {
NSString *query = @"SELECT uid,imgstr,name,descrite FROM userName";
if (!uid) {
query = [query stringByAppendingFormat:@" ORDER BY uid DESC limit %d",limit];
} else {
query = [query stringByAppendingFormat:@" WHERE uid > %@ ORDER BY uid DESC limit %d",uid,limit];
}
FMResultSet *resultSet = [db executeQuery:query];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[resultSet columnCount]];
while ([resultSet next]) {
YJUserModel *userModel = [YJUserModel new];
userModel.uid = [resultSet stringForColumn:@"uid"];
userModel.imgstr = [resultSet stringForColumn:@"imgstr"];
userModel.name = [resultSet stringForColumn:@"name"];
userModel.descrite = [resultSet stringForColumn:@"descrite"];
[array addObject:userModel];
}
[resultSet close];
return array;
}
/**
* @brief 查詢用戶的信息
*
* @param name 查詢的用戶信息名稱
*
* @bools 標識是否是全稱查詢/模糊查詢? YES(單個查詢) ? NO (模糊查詢)
*/
- (NSArray *)selectWithName:(NSString *)name Bools:(BOOL)bools
{
NSString *query = [NSString string];
if ([[NSString string] isPureInt:name] || [[NSString string] isPureFloat:name]) {
query = [NSString stringWithFormat:@"SELECT uid,imgstr,name,descrite FROM userName where uid=\"%@\"",name];
}else{
if (bools) {
query = [NSString stringWithFormat:@"SELECT uid,imgstr,name,descrite FROM userName where name=\"%@\"",name];
}else{
query = [NSString stringWithFormat:@"SELECT uid,imgstr,name,descrite FROM userName where name like \"%%%@%%\"",name];
}
}
//將數(shù)據(jù)庫中的數(shù)據(jù)放到一個集合類FMResultSet中
FMResultSet *resultSet = [db executeQuery:query];
//創(chuàng)建一個動態(tài)數(shù)組
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[resultSet columnCount]];
//將集合中的數(shù)據(jù)循環(huán)取出,并賦給變動數(shù)組灌旧,返回值為這個變動數(shù)組
while ([resultSet next]) {
YJUserModel *userModel = [YJUserModel new];
userModel.uid = [resultSet stringForColumn:@"uid"];
userModel.imgstr = [resultSet stringForColumn:@"imgstr"];
userModel.name = [resultSet stringForColumn:@"name"];
userModel.descrite = [resultSet stringForColumn:@"descrite"];
[array addObject:userModel];
}
[resultSet close];
return array;
}
/**
* @brief 清除所有用戶的信息
*
* @param name? 謹記:刪除之后哪里使用到數(shù)據(jù)庫需要重新初始化數(shù)據(jù)
*
* @bools DELETE FROM 刪除數(shù)據(jù)庫文件
*/
- (void)deleteUserInfoWithDB
{
NSString * docp = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *name = [docp stringByAppendingString:[NSString stringWithFormat:@"/%@",kDefaultDBName]];
db = [FMDatabase databaseWithPath:name];
[db open];
BOOL success =? [db executeUpdate:@"DELETE FROM userName"];
if (success) {
NSLog(@"刪除全部數(shù)據(jù)");
}
[db close];
}
到這就結(jié)束了FMDB 的封裝绑咱,使用的時候根據(jù)你自己的數(shù)據(jù)模型類型創(chuàng)建添加到你的封裝的類里面進行數(shù)據(jù)的處理。
下面看一下效果圖
插入一條數(shù)據(jù):
模糊查詢:
單個查詢枢泰、刪除描融、修改的就不在發(fā)效果圖了,有想了解的需要源碼的call我郵箱(bj_yj1991@126.com)留言衡蚂,我發(fā)源碼給大家分享窿克。