您的位置:首页 > 其它

FMDB基本使用

2016-04-11 08:13 302 查看
#import "PersonDBTool.h"
#import <FMDB.h>

@implementation PersonDBTool

static FMDatabase *_dataBase;

+ (void)initialize{
//1.创建数据,并且打开/连接到沙盒中的数据库
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSString *filePath = [documentPath stringByAppendingPathComponent:@"person.db"];

_dataBase = [FMDatabase databaseWithPath:filePath];

//2.打开
BOOL result = [_dataBase open];

if(result){
//3.创建表
BOOL createTableResult = [_dataBase executeUpdate:@"create table if not exists t_person(id integer primary key,name text,age integer);"];

if(createTableResult){
NSLog(@"create Table ok!!!");
}else{
NSLog(@"error!!!");
}
}
}

#pragma mark - FMDB DML语句
+ (void)insertPerson:(Person *)person{
[_dataBase executeUpdateWithFormat:@"insert into t_person(name,age) values(%@,%d) ;",person.name,person.age];
}

+ (void)updatePerson:(Person *)person{
[_dataBase executeUpdateWithFormat:@"update t_person set age = %d where name = %@",person.age,person.name];
}

+ (void)deletePersonWithId:(int)personId{
[_dataBase executeUpdateWithFormat:@"delete from t_person where id = %d",personId];
}

#pragma mark - DQL语句
+ (NSArray *)queryAllPerson{
NSMutableArray *persons = [NSMutableArray array];

FMResultSet *resultSet = [_dataBase executeQuery:@"select * from t_person"];

while ([resultSet next]) {//遍历到每一条记录
NSString *pname = [resultSet stringForColumn:@"name"];
int age = [resultSet intForColumn:@"age"];

Person *p = [[Person alloc] init];
p.name = pname;
p.age = age;

[persons addObject:p];
}

return persons.copy;
}

+ (NSArray *)queryPersonWithKeyWord:(NSString *)keyWord{
NSMutableArray *persons = [NSMutableArray array];

FMResultSet *resultSet = [_dataBase executeQuery:[NSString stringWithFormat:@"select * from t_person where name like '%%%@%%';",keyWord]];

while ([resultSet next]) {//遍历到每一条记录
NSString *pname = [resultSet stringForColumn:@"name"];
int age = [resultSet intForColumn:@"age"];

Person *p = [[Person alloc] init];
p.name = pname;
p.age = age;

[persons addObject:p];
}

return persons.copy;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: