FMDB

static ShareData *fm = nil;

static FMDatabase *fmdb = nil;

@implementation ShareData

+(ShareData *)sharedata{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

fm = [[ShareData alloc]init];

[fm initDB];

});

return fm;

}

+(instancetype)allocWithZone:(struct _NSZone *)zone{

if (fm == nil ) {

fm = [super allocWithZone:zone];

}

return fm;

}

-(id)copy{

return self;

}

-(id)mutableCopy{

return self;

}

-(void)initDB{

NSString *docment = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];

NSString *path = [docment stringByAppendingPathComponent:@"XH.sqlite"];

fmdb = [[FMDatabase alloc]initWithPath:path];

if ([fmdb open]) {

[fmdb executeUpdate:@"create table class (tagId integer primary key autoincrement, name text,age text,like text)"];

[fmdb close];

}else{

NSLog(@"数据表创建失败");

}

}

-(NSMutableArray *)Marr{

NSMutableArray *Arr = [NSMutableArray array];

[fmdb open];

FMResultSet *fmset = [[FMResultSet alloc]init];

fmset = [fmdb executeQuery:@"select * from class"];

while ([fmset next]) {

Data *d = [[Data alloc]init];

d.tabId = [fmset intForColumn:@"tagId"];

d.name = [fmset stringForColumn:@"name"];

d.age = [fmset stringForColumn:@"age"];

d.like = [fmset stringForColumn:@"like"];

[Arr addObject:d];

}

[fmdb close];

return Arr;

}

-(void)addData:(Data *)AddD{

BOOL isc = false;

NSArray *arr = [self Marr];

for (Data *d in arr) {

if ([d.name isEqualToString:AddD.name]&&[d.age isEqualToString:AddD.age]&&[d.like isEqualToString:AddD.like]) {

isc = true;

}

}

if (isc) {

NSLog(@"数据相同");

}else{

[fmdb open];

BOOL isb = [fmdb executeUpdate:@"insert into class values(null,?,?,?)",AddD.name,AddD.age,AddD.like];

if (isb) {

NSLog(@"添加成功");

}else{

NSLog(@"添加失败");

}

}

[fmdb close];

}

-(void)RemoveData:(Data*)deleteData{

[fmdb open];

NSString *sql = [NSString stringWithFormat:@"DELETE FROM class WHERE tagId =%ld",deleteData.tabId];

BOOL isb = [fmdb executeUpdate:sql];

if (isb) {

NSLog(@"删除成功");

}else{

NSLog(@"删除失败");

}

[fmdb close];

}

-(void)UpData:(Data *)Updata{

[fmdb open];

NSString *str = [NSString stringWithFormat:@"update class set name = '%@',age = '%@', like = '%@' where tagId = %ld",Updata.name,Updata.age,Updata.like,Updata.tabId];

BOOL isb = [fmdb executeUpdate:str];

if (isb) {

NSLog(@"修改成功");

}else{

NSLog(@"修改失败");

}

[fmdb close];

}

你可能感兴趣的:(FMDB)