首页 > 代码库 > FMDB的增删改查
FMDB的增删改查
+ (ZSDataHandle *)shareDataHandle
{
static ZSDataHandle *dataHandle = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (dataHandle == nil) {
dataHandle = [[ZSDataHandle alloc] init];
}
});
return dataHandle;
}
- (instancetype)init
{
self = [super init];
if (self) {
NSString *filePaht = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"%@",filePaht);
NSString *dbPath = [filePaht stringByAppendingString:@"zs.sqlite"];
_db = [FMDatabase databaseWithPath:dbPath];
if ([_db open]) {
BOOL result = [_db executeUpdate:@"create table Students (number Integer Primary Key autoIncrement,age NSInteger default 15,name text not NULL)"];
NSLog(@"%d",result);
[_db close];
}
}
return self;
}
//增加
- (void)insertWithNumber:(NSInteger)number name:(NSString *)name age:(NSInteger)age
{
if ([_db open]) {
BOOL result = [_db executeUpdate:@"insert into Students (number,name,age) values (?,?,?)",[NSNumber numberWithInteger:number],name,[NSNumber numberWithInteger:age]];
NSLog(@"%d",result);
[_db close];
}
}
//删除
- (void)deleteWithnumber:(NSInteger)number
{
if ([_db open]) {
BOOL result = [_db executeUpdate:@"delete from Students where number = ?",[NSNumber numberWithInteger:number]];
NSLog(@"%d",result);
[_db close];
}
}
//查询
- (NSMutableArray *)selectWithWithNumber:(NSInteger)number
{
NSMutableArray *array = [NSMutableArray array];
if ([_db open]) {
FMResultSet *result = [_db executeQuery:@"select name from Students where number = ?",[NSNumber numberWithInteger:number]];
if ([result next]) {
[array addObject:[result stringForColumn:@"name"]];
}
[_db close];
}
return array;
}