iOS --- FMDB简单封装存储数据

testFMDB.h

import 
#import "testModel.h"

@interface testFMDB : NSObject
//获取
+(NSArray *)testData;
//添加
+(void)addTestModel:(testModel *)model testId:(NSString *)testId;
//移除
+ (void)removeTestData:(NSString *)testId;
@end

testFMDB.m

#import "testFMDB.h"
#import "FMDB.h"

@implementation testFMDB

static FMDatabase *_db;


+ (void)initialize
{
    // 1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"playHistory.sqlite"];
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open]) return;
    
    // 2.创表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_testData (id integer PRIMARY KEY AUTOINCREMENT,testId text NOT NULL,testModel blob NOT NULL);"];
  
    
}

//查询
+(NSArray *)movieData{

    NSString *sql = @"SELECT * FROM t_testData ORDER BY id DESC;";
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *statuses = [NSMutableArray array];
    
    while (set.next) {
        NSData *statusData = [set objectForColumnName:@"testModel"];
        testModel *testmodel = [NSKeyedUnarchiver unarchiveObjectWithData:statusData];
        
        [statuses addObject:testmodel];
    }
    return statuses;
}


//增加
+(void)addMovieInfo:(testModel *)model testId:(NSString *)testId{
    
    // model --> NSData
    NSData *statusData = [NSKeyedArchiver archivedDataWithRootObject:model];
    [_db executeUpdateWithFormat:@"INSERT INTO t_testData(testId,testModel) VALUES (%@,%@);", testId,statusData];
    
}

//移除
+ (void)removeTestData:(NSString *) testId{
    [_db executeUpdateWithFormat:@"DELETE FROM t_testData WHERE testId = %@;", testId];
    
}
@end

你可能感兴趣的:(iOS --- FMDB简单封装存储数据)