<pre name="code" class="objc">#import "FMDBManager.h"
#import "FMDatabase.h"
#import "FMResultSet.h"//搜索的结果
@interface FMDBManager ()
{
FMDatabase *db;
}
@end
@implementation FMDBManager
static FMDBManager *fmdb = nil;
+ (instancetype) sharedManager
{
@synchronized(self)
{
if (fmdb == nil)
{
fmdb = [[FMDBManager alloc] init];
}
}
return fmdb;
}
//sqlite语句
/*增insert into 表名 (applicationId,name,iconUrl) values (?,?,?)*/
/*删delete from 表名 where applicationId = ?*/
/*改 update 表名 set 属性名 = ? where applicationId = ?*/
/*查询某一个是否存在select applicationId from 表名 where applicationId = ?*/
/* 查询所有的数据select * from 表名 */
- (instancetype) init
{
if (self = [super init])
{
//创建数据库 需要接收一个沙盒路径
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/heros.db"];
NSLog(@"%@",path);
db = [[FMDatabase alloc] initWithPath:path];
BOOL success = [db open];
if (success)
{
NSString *sql = @"create table if not exists hero(name varchar(32),icon varchar(128),intro varchar(1024)) ";
BOOL tableIsCreate = [db executeUpdate:sql];
if (tableIsCreate)
{
NSLog(@"success to create table");
}
else
{
NSLog(@"failed to create table");
}
}
else
{
NSLog(@"Failed to open database");
}
}
return self;
}
- (BOOL) insertDataWithDictionary:(NSDictionary *)heroDic
{
NSString *sql = @"insert into hero (name,icon,intro) values (?,?,?)";
BOOL isSuccess = [db executeUpdate:sql,heroDic[@"name"],heroDic[@"icon"],heroDic[@"intro"]];
if (isSuccess)
{
NSLog(@"insert success");
}
else
{
NSLog(@"insert failed!");
}
return isSuccess;
}
- (BOOL) deleteDataWithDictionary:(NSDictionary *)heroDic
{
NSString *sql = @"delete from hero where name = ?";
BOOL isSuccess = [db executeUpdate:sql,heroDic[@"name"]];
if (isSuccess)
{
NSLog(@"delete success");
}
else
{
NSLog(@"delete failed");
}
return isSuccess;
}
- (BOOL) updateDataWithName:(NSString *)name changeIntro:(NSString *)intro
{
//前一个参数 是你需要修改的内容
//后一个参数 是你需要根据某一个内容查找到你需要修改的信息
NSString *sql = @"update hero set intro = ? where name = ?";
BOOL isSuccess = [db executeUpdate:sql,intro,name];
if (isSuccess)
{
NSLog(@"update success");
}
else
{
NSLog(@"update failed");
}
return isSuccess;
}
- (NSMutableArray *)receiveData
{
NSString *sql = @"select * from hero ";
FMResultSet *results = [db executeQuery:sql];
NSMutableArray *dataArray = [NSMutableArray array];
while ([results next])
{
NSDictionary *dic = [results resultDictionary];
[dataArray addObject:dic];
}
return dataArray;
}
@end
#import <Foundation/Foundation.h>@interface FMDBManager : NSObject+ (instancetype) sharedManager;//插入数据库- (BOOL) insertDataWithDictionary:(NSDictionary *)heroDic;//删除一条数据- (BOOL) deleteDataWithDictionary:(NSDictionary *)heroDic;//更新一条数据- (BOOL) updateDataWithName:(NSString *)name changeIntro:(NSString *)intro;//查询所有数据,并且返回数据 LKDBHelper- (NSMutableArray *)receiveData;@end