数据库在开发过程是常用到的数据处理工具,在以后的开发过程中也会常常用到,下面我来浅谈一下框架 FMDB的封装使用方案。
首先,我们来封装一个FMDB的BaseManager管理者,在.h文件里添加一个数据库操作对象属性:@property (nonatomic, readonly) FMDatabase *dataBase以及你数据库地址的一个属性;
创建一个管理单例对象:+(YJDataBaseManager *)defaultDBManager;
创建一个连接数据库方法:- (void)connect;
关闭数据库的方法:- (void)close;
在你的.m文件实现方法:首先初始化数据库管理者:+ (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(@"数据库初始化失败");
} else {
NSLog(@"😄数据库初始化成功");
}
}
return self;
}- (id)init {
self = [super init];
if (self) {
int state = [self initializeDBWithName:kDefaultDBName];
if (state == -1) {
NSLog(@"数据库初始化失败");
} else {
NSLog(@"😄数据库初始化成功");
}
}
return self;
}
返回数据库初始化状态(0 为 已经存在,1 为创建成功,-1 为创建失败)
- (int)initializeDBWithName:(NSString *)nameStr
{
if (!nameStr) {
return -1; // 返回数据库创建失败
}
// 沙盒Docu目录
NSString * docp = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
name = [docp stringByAppendingString:[NSString stringWithFormat:@"/%@",nameStr]];
NSLog(@"数据库地址-----------%@",name);
NSFileManager * fileManager = [NSFileManager defaultManager];
BOOL exist = [fileManager fileExistsAtPath:name];
[self connect];
if (!exist) {
return 0;
} else {
return 1;
}
}
连接数据库
- (void)connect
{
if (!_dataBase) {
//根据文件路径来创建FMDatabase对象
_dataBase = [[FMDatabase alloc] initWithPath:name];
}
if (![_dataBase open]) {
NSLog(@"不能打开数据库");
}
}
关闭连接
- (void)close
{
[_dataBase close];
sharedDBManager = nil;
}
到这里已经结束了FMDB管理者的定义封装,接下来我们创建一个用户数据处理的端口,主要用来进行数据的模糊查找、数据添加、数据删除、数据修改的方法。首先在.h文件添加如下方法:
user 需要保存的用户数据:- (void)saveUser:(YJUserModel *)userModel;
uid 需要删除的用户的id:- (void)deleteUserInfoWithId:(NSString *)uid;
需要修改的用户信息:- (void)mergeWithUser:(YJUserModel *)userModel;
模拟分页查找数据:-(NSArray *)findWithUid:(NSString *)uid limit:(int)limit;
标识是否是全称查询or模糊查询 YES(单个查询) ? NO (模糊查询):- (NSArray *)selectWithName:(NSString *)name Bools:(BOOL)bools;
删除数据库文件:- (void)deleteUserInfoWithDB;
创建数据库:- (void)createDataBase;
在.m文件实现以上方法
- (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:数据库已存在
NSLog(@"数据库已存在");
}else{//TODO: 插入新的数据库数据
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(@"数据库创建失败");
}else{
NSLog(@"数据库创建成功");
}
}
}
/**
* @brief 保存一条用户记录
*
* @param userModel 需要保存的用户数据
*/
- (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(@"插入一条数据");
}
}
/**
* @brief 删除一条用户数据
*
* @param uid 需要删除的用户的id
*/
- (void)deleteUserInfoWithId:(NSString *)uid
{
NSString *query = [NSString stringWithFormat:@"DELETE FROM userName WHERE uid = '%@'",uid];
if ([db executeUpdate:query]) {
NSLog(@"删除一条数据");
}
}
/**
* @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(@"修改数据/成功");
}else{
NSLog(@"修改数据/失败");
}
}
/**
* @brief 模拟分页查找数据。取uid大于某个值以后的limit个数据
*
* @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];
}
}
//将数据库中的数据放到一个集合类FMResultSet中
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 DELETE FROM 删除数据库文件
*/
- (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(@"删除全部数据");
}
[db close];
}
到这就结束了FMDB 的封装,使用的时候根据你自己的数据模型类型创建添加到你的封装的类里面进行数据的处理。
下面看一下效果图
插入一条数据:
模糊查询:
单个查询、删除、修改的就不在发效果图了,有想了解的需要源码的call我邮箱(bj_yj1991@126.com)留言,我发源码给大家分享。