三、Sqlite3

2018-01-22  本文已影响3人  faterman

SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。主流嵌入式数据库系统,主要特点是轻量级,跨平台。基本的使用可参考:
sqlite官方文档
iOS开发-sqlite3使用


其实关于数据库的概念和使用并不多。我实际用一个需求来记录一下。

我们目前需要一个应用通知系统,通知系统用于存放应用收到的远程通知,并标明已读、未读状态,和需要跳转界面的URL。

根据需求先搭建一个框架:

// FTMRemoteMessageCenter.h 文件

#import <Foundation/Foundation.h>

@interface FTMRemoteMessage : NSObject

@property (copy, nonatomic) NSString *content;
@property (copy, nonatomic) NSString *redirectUrl;
@property (assign, nonatomic, getter=isRead) BOOL read;

@end

@interface FTMRemoteMessageCenter : NSObject
/// 单例方法
+ (instancetype)defaultCenter;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;

- (void)insertMessage:(FTMRemoteMessage *)message;
- (void)deleteMessage:(FTMRemoteMessage *)message;
- (NSArray <FTMRemoteMessage *>*)allMessages;

@end
//  FTMRemoteMessageCenter.m

#import "FTMRemoteMessageCenter.h"
#import <sqlite3.h>
#import <pthread/pthread.h>

@implementation FTMRemoteMessage

@end

#define Lock() pthread_mutex_lock(&_lock)
#define Unlock() pthread_mutex_unlock(&_lock)

static FTMRemoteMessageCenter *center = nil;

@implementation FTMRemoteMessageCenter {
    sqlite3 *_db;
    pthread_mutex_t _lock; // 互斥锁
}

+ (instancetype)defaultCenter {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        center = [[self alloc]init];
    });
    return center;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        pthread_mutex_init(&_lock, NULL);
        [self createTable];
    }
    return self;
}

- (BOOL)openDB {
    
    Lock();
    
    NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"remote_message.db"];
    NSLog(@"%@",dbPath);
    int result = sqlite3_open(dbPath.UTF8String, &_db);
    if (result == SQLITE_OK) {
        return YES;
    }
    return NO;
}

- (BOOL)closeDB {
    int result = sqlite3_close(_db) ;
    if (result != SQLITE_OK) {
        NSLog(@"数据库关闭失败");
        return NO;
    }
    Unlock();
    return YES;
}

- (void)createTable {
    [self openDB];
    const char *createSQL = "create table if not exists message(id integer primary key autoincrement,content char,redirect_url char,read int)";
    char *error;
    int tableResult = sqlite3_exec(_db, createSQL, NULL, NULL, &error);
    if (tableResult != SQLITE_OK) {
        NSLog(@"创建表失败:%s",error);
    }
    [self closeDB];
}



// 防止c层是用者通过kvc修改业务层值
+ (BOOL)accessInstanceVariablesDirectly {
    return NO;
}

- (void)insertMessage:(FTMRemoteMessage *)message {
    [self openDB];
    NSString *sqlStr = [NSString stringWithFormat:@"insert into message (content, redirect_url, read) values (%@, %@, %d)",message.content, message.redirectUrl, message.isRead];
    sqlite3_stmt *stmt=NULL;
    int insertResult = sqlite3_prepare_v2(_db, sqlStr.UTF8String, -1, &stmt, nil);
    if (insertResult != SQLITE_OK) {
        NSLog(@"添加失败,%d",insertResult);
    }else {
        sqlite3_step(stmt);
    }
    sqlite3_finalize(stmt); // 回收句柄资源
    [self closeDB];
}

- (void)deleteMessage:(FTMRemoteMessage *)message {
    [self openDB];
    NSString *sqlStr = [NSString stringWithFormat:@"delete from message where content = '%@'",message.content];
    sqlite3_stmt *stmt=NULL;
    int deleteResult = sqlite3_prepare(_db, sqlStr.UTF8String, -1, &stmt, nil);
    if (deleteResult != SQLITE_OK) {
        NSLog(@"删除失败,%d",deleteResult);
    }else {
        sqlite3_step(stmt);
    }
    sqlite3_finalize(stmt); // 回收句柄资源
    [self closeDB];
}

- (NSArray<FTMRemoteMessage *> *)allMessages {
    [self openDB];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    const char *searchSQL = "select content,redirect_url,read from message";
    sqlite3_stmt *stmt = NULL;
    int searchResult= sqlite3_prepare(_db, searchSQL, -1, &stmt, nil);
    if (searchResult != SQLITE_OK) {
        NSLog(@"查询失败,%d",searchResult);
        return nil;
    }else {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            FTMRemoteMessage *message = [[FTMRemoteMessage alloc]init];
            message.content = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 0)];
            message.redirectUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
            message.read = sqlite3_column_int(stmt, 2);
            [array addObject:message];
        }
    }
    sqlite3_finalize(stmt); // 回收句柄资源
    [self closeDB];
    return array;
}

常见的一些问题

  1. 如何调试数据库错误
// 可打印详细错误信息
NSLog(@"添加失败,%d,%s",insertResult,sqlite3_errmsg(_db));
  1. 如何插入特殊字符

/ -> //
' -> ''
[ -> /[
] -> /]
% -> /%
& -> /&
_ -> /_
( -> /(
) -> /)

若果字符串中包含'<',可采取sqlite3_bind_text方式:

/*
    FTMRemoteMessage *msg = [[FTMRemoteMessage alloc]init];
    msg.content = @"<html>这是一个网页<html>";
    msg.redirectUrl = @"123";
     */
    NSString *sqlStr = [NSString stringWithFormat:@"insert into message (content) values (?)"];
    sqlite3_stmt *stmt=NULL;
    int insertResult = sqlite3_prepare_v2(_db, sqlStr.UTF8String, -1, &stmt, nil);
    sqlite3_bind_text(stmt, 1, message.content.UTF8String, -1, SQLITE_STATIC);

    if (insertResult != SQLITE_OK) {
        NSLog(@"添加失败,%d,%s",insertResult,sqlite3_errmsg(_db));
    }else {
        sqlite3_step(stmt);
    }
    sqlite3_finalize(stmt); // 回收句柄资源
  1. 支持的基本类型
  1. 数据库如何升级
    当然,笨办法就是升级就删除db,数据就不要了,重新获取。这种方式毕竟还是不提倡的,因为有些数据是持久化到本地,并不能从其它地方获取。主要有以下集中情况:
  1. 多线程
    Sqlite支持三种线程模式:
上一篇下一篇

猜你喜欢

热点阅读