#import <Foundation/Foundation.h>
#import "Book.h"
#import "FMDatabase.h"
@interface FMDBBookHandle : NSObject
+(instancetype)sharedFMDB;
//创建增删改查单例
-(void)insertBook:(Book *)book;
-(void)deleteBook:(Book *)book;
-(void)updateBook:(Book *)book;
-(NSMutableArray *)selectAll;
//上文的book是模型类,用来传值。
#import "FMDBBookHandle.h"
#import "FMResultSet.h"
//实现上文我们所写的单例方法
static FMDBBookHandle *fmBook;
static FMDatabase *fmdb;
@implementation FMDBBookHandle
+(instancetype)sharedFMDB
{
if (!fmBook) {
fmBook = [[FMDBBookHandle alloc]init];
[fmBook initFMDB];
}
return fmBook;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
if (!fmBook) {
fmBook = [super allocWithZone:zone];
}
return fmBook;
}
-(id)mutableCopy
{
return self;
}
-(id)copy
{
return self;
}
-(void)initFMDB
{
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *path = [docPath stringByAppendingPathComponent:@"chenrui.sqlite"];
NSLog(@"%@",path);
fmdb = [FMDatabase databaseWithPath:path];
if ([fmdb open]) {
[fmdb executeUpdate:@"CREATE TABLE book(idd INTEGER PRIMARY KEY AUTOINCREMENT , name TEXT, author TEXT, price TEXT)"];
[fmdb close];
}
else
NSLog(@"创建数据表失败");
}
-(NSMutableArray *)selectAll
{
NSMutableArray *arr = [NSMutableArray array];
[fmdb open];
FMResultSet *fmSet = [[FMResultSet alloc]init];
fmSet = [fmdb executeQuery:@"SELECT * FROM book"];
while ([fmSet next]) {
int idd = [fmSet intForColumn:@"idd"];
NSString *name = [fmSet stringForColumn:@"name"];
NSString *author = [fmSet stringForColumn:@"author"];
NSString *price = [fmSet stringForColumn:@"price"];
Book *b = [[Book alloc]init];
b.idd = idd;
b.name = name;
b.author = author;
b.price = price;
NSLog(@"id = %d",idd);
[arr addObject:b];
}
[fmdb close];
return arr;
}
-(void)insertBook:(Book *)book
{
BOOL flag = false;
NSArray *arrBook = [self selectAll];
for (Book *b in arrBook) {
if ([b.name isEqualToString:book.name ] && [b.author isEqualToString:book.author] && [b.price isEqualToString:book.price]) {
flag = true;
}
}
if (flag) {
NSLog(@"数据相同");
}
else
{
[fmdb open];
BOOL addFlag = [fmdb executeUpdate:@"INSERT INTO book VALUES(null,?,?,?)",book.name,book.author,book.price ];
if (addFlag) {
NSLog(@"添加成功");
}
else
{
NSLog(@"添加失败");
}
[fmdb close];
}
}
-(void)deleteBook:(Book *)book
{
[fmdb open];
NSString *sql = [NSString stringWithFormat:@"DELETE FROM book WHERE idd = %d",book.idd];
BOOL deleteFlag = [fmdb executeUpdate:sql];
if (deleteFlag) {
NSLog(@"删除成功");
}
else
NSLog(@"删除失败");
[fmdb close];
}
-(void)updateBook:(Book *)book
{
[fmdb open];
NSString *sql = [NSString stringWithFormat:@"UPDATE book SET name = ‘%@‘,author = ‘%@‘,price = ‘%@‘ WHERE idd = %d",book.name,book.author,book.price,book.idd];
bool updateFlag = [fmdb executeUpdate:sql];
if (updateFlag) {
NSLog(@"修改成功");
}
else
NSLog(@"修改失败");
[fmdb close];
}
@end