ios開發:使用sqlite存儲數據

若是想在ios本地存儲複雜的數據結構,sqlite是不錯的選擇。 使用sqlite,首先須要在項目中引入類庫libsqlite3 引入以後,開始寫dao類,操做數據庫,下面是代碼示例: dao.hios

(void)createEditableCopyOfDatabaseIfNeeded;

//插入菜餚的方法
- (int) create: (Cai *)model;

//刪除菜餚的方法
- (int) remove: (Cai *)model;

//修改菜餚的方法
//- (int) modify: (Cai *)model;

//查詢全部數據的方法
- (NSMutableArray *) findAll;

//按照分類id查詢數據的方法
- (NSMutableArray *) findByClassId: (Cai *)model;

@end

dao.m文件sql

#import "CaiDao.h"

@implementation CaiDao

static CaiDao *sharedManager = nil;
+ (CaiDao*)sharedManager
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        
        sharedManager = [[self alloc] init];
        [sharedManager createEditableCopyOfDatabaseIfNeeded];
        
        
    });
    return sharedManager;
}

- (NSString *)applicationDocumentsDirectoryFile{
    
    NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [documentDirectory stringByAppendingPathComponent:DBFILE_NAME];
    
    return path;
}

- (void)createEditableCopyOfDatabaseIfNeeded {
    NSString *writableDBPath = [self applicationDocumentsDirectoryFile];
    
    if (sqlite3_open([writableDBPath UTF8String], &db) != SQLITE_OK){
        sqlite3_close(db);
        NSAssert(NO, @"數據庫打開失敗...");
    } else{
        char *err;
        NSString *createSQL = [NSString stringWithFormat:@"create table if not exists Cai (id text primary key, foodName text, classId text);"];
        if(sqlite3_exec(db, [createSQL UTF8String], nil, nil, &err) != SQLITE_OK){
            sqlite3_close(db);
            NSAssert(NO, @"建表失敗, %s", err);
        }
        sqlite3_close(db);
    }
}
//插入菜餚
-(int) create:(Cai *)model{
    
    NSString *path = [self applicationDocumentsDirectoryFile];
    
    if (sqlite3_open([path UTF8String], &db) != SQLITE_OK) {
        sqlite3_close(db);
        NSAssert(NO,@"數據庫打開失敗。");
    } else {
        
        NSString *sqlStr = @"INSERT OR REPLACE INTO cai (id, foodName, classId) VALUES (?,?,?)";
        
        sqlite3_stmt *statement;
        //預處理過程
        if (sqlite3_prepare_v2(db, [sqlStr UTF8String], -1, &statement, nil) == SQLITE_OK) {
            
            //綁定參數開始
            sqlite3_bind_text(statement, 1, [model.id UTF8String], -1, nil);
            sqlite3_bind_text(statement, 2, [model.foodName UTF8String], -1, nil);
            sqlite3_bind_text(statement, 3, [model.classId UTF8String], -1, nil);
            
            //執行插入
            if (sqlite3_step(statement) != SQLITE_DONE) {
                NSAssert(NO, @"插入數據失敗。");
            }
        }else {
            NSAssert1(0,@"Error:%s",sqlite3_errmsg(db));
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(db);
    }
    
    return 0;
}

//根據菜餚種類id查詢菜餚列表
- (NSMutableArray *) findByClassId:(Cai *)model{
    NSString *path = [self applicationDocumentsDirectoryFile];
    NSMutableArray *listData = [[NSMutableArray alloc] init];
    
    if (sqlite3_open([path UTF8String], &db) != SQLITE_OK){
        sqlite3_close(db);
        NSAssert(NO, @"數據庫打開失敗...");
    } else{
        NSString *qsql = @"select id, foodName, classId from cai where classId = ?";
        sqlite3_stmt * statement;
        //預處理過程
        if(sqlite3_prepare_v2(db, [qsql UTF8String], -1, &statement, nil) == SQLITE_OK){
            //準備參數
            NSString *classid = model.classId;
            
            //綁定參數開始
            sqlite3_bind_text(statement, 1, [classid UTF8String], -1, nil);
            
            //執行
            while (sqlite3_step(statement) == SQLITE_ROW){
                char *cai_id = (char *) sqlite3_column_text(statement, 0);
                NSString *caiId = [[NSString alloc] initWithUTF8String:cai_id];
                
                char *food_name = (char *) sqlite3_column_text(statement, 1);
                NSString *foodName = [[NSString alloc] initWithUTF8String:food_name];
                
                char *class_id = (char *) sqlite3_column_text(statement, 2);
                NSString *classId = [[NSString alloc] initWithUTF8String:class_id];
                
                Cai *cai = [[Cai alloc] init];
                cai.id = caiId;
                cai.foodName = foodName;
                cai.classId = classId;
                
                [listData addObject:cai];
            }
        }
        sqlite3_finalize(statement);
        sqlite3_close(db);
    }
    
    return listData;
}


//查詢全部菜餚列表
- (NSMutableArray *) findAll{
    NSString *path = [self applicationDocumentsDirectoryFile];
    NSMutableArray *listData = [[NSMutableArray alloc] init];
    
    if (sqlite3_open([path UTF8String], &db) != SQLITE_OK){
        sqlite3_close(db);
        NSAssert(NO, @"數據庫打開失敗...");
    } else{
        NSString *qsql = @"select id, foodName, classId from cai";
        sqlite3_stmt * statement;
        //預處理過程
        if(sqlite3_prepare_v2(db, [qsql UTF8String], -1, &statement, nil) == SQLITE_OK){
            
            //執行
            while (sqlite3_step(statement) == SQLITE_ROW){
                char *cai_id = (char *) sqlite3_column_text(statement, 0);
                NSString *caiId = [[NSString alloc] initWithUTF8String:cai_id];
                
                char *food_name = (char *) sqlite3_column_text(statement, 1);
                NSString *foodName = [[NSString alloc] initWithUTF8String:food_name];
                
                char *class_id = (char *) sqlite3_column_text(statement, 2);
                NSString *classId = [[NSString alloc] initWithUTF8String:class_id];
                
                Cai *cai = [[Cai alloc] init];
                cai.id = caiId;
                cai.foodName = foodName;
                cai.classId = classId;
                
                [listData addObject:cai];
            }
        }
        sqlite3_finalize(statement);
        sqlite3_close(db);
    }
    
    return listData;
}


@end

其中用到的model Cai類:數據庫

#import <Foundation/Foundation.h>

@interface Cai : NSObject

@property NSString *id;
@property NSString *foodName;
@property NSString *classId;
@property NSString *price;
@property NSString *foodPinyin;
@property NSString *sujima;

@end

在須要插入數據或者取出數據的地方這樣寫:數據結構

CaiDao *dao = [CaiDao sharedManager];
    Cai *cai = [[Cai alloc] init];
    cai.id = @"111";
    cai.foodName = @"紅燒排骨";
    cai.classId = @"recai";
    [dao create:cai];
    
    NSMutableArray *array = [dao findAll];
    for(Cai *c in array)
    {
        [[[Utils alloc] init] showAlert:c.foodName :self];
    }

大功告成!app

相關文章
相關標籤/搜索