iOS数据存储(四)SQLite 3

SQLite是一个开源的嵌入式关系数据库,它的减少应用程序管理数据的开销,SQLite可移植性好,很容易使用,很小,高效而且可靠。

第一步:引入PLDatabase库
第二步:创建.spl文件【create_db.spl】
第三步:
CDSqlManager.h

#import <Foundation/Foundation.h>
#import "PlausibleDatabase.h"

@interface CDSqlManager : NSObject
//sql执行函数
+(id<PLResultSet>) executeQueryWithSqlString: (NSString *) sqlString;

// 不加锁执行sq
+(void) executeUpdateWithoutLockWithSqlString:(NSString *)sqlString;

//执行更新语句
+(BOOL) executeUpdateWithSqlString: (NSString *) sqlString;

//执行sql语句,在初始化表时执行
+(void) executeSqlWithSqlStrings: (NSString *) sqlStrings;

// 判断表是否存在
+(BOOL) dbExists;

//打开数据库
+(void) openDatabase;

// 关闭数据库表
+(void) closeDatabase;

//加锁
+(void) lock;

 函数描述: 解锁
+(void) unlock;

CDSqlManager.m

#import "CDSqlManager.h"
#import "PlausibleDatabase.h"

#define sqlFileName @"CDDemoSqlFile"
@implementation CDSqlManager
// database类型:类静态变量
static PLSqliteDatabase *database = nil;
static NSCondition *condition = nil;

+(NSString *) dbPath
{
    static NSString *dbPath = nil;
    
    if (!dbPath)
    {
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
        dbPath = [[documentPath stringByAppendingString:sqlFileName]retain];
    }
    
    return dbPath;
}

+(BOOL) dbExists
{
    return [[NSFileManager defaultManager] fileExistsAtPath: [self dbPath]];
}

+ (void)openDatabase
{
    if(nil == database)
    {
        database = [[PLSqliteDatabase alloc] initWithPath: [self dbPath]];
        BOOL bOpen = [database open];
        
        NSLog(@"dbPath = %@, bOpen = %d", [self dbPath], bOpen);
        
        if (bOpen)
        {
            NSLog(@"Database opened OK!");
        }
        
        condition = [[NSCondition alloc] init];
    }
}

+(void) closeDatabase
{
    [condition release];
    [database release];
}

+(void) lock
{
    [condition lock];
}

+(void) unlock
{
    [condition unlock];
}

#pragma mark -

+(id<PLResultSet>) executeQueryWithSqlString: (NSString *) sqlString
{
    NSLog(@"%s %d, sqlString = %@", __FUNCTION__, __LINE__, sqlString);

    if (nil == sqlString)
    {
        return nil;
    }
    
//    [self lock];//数据库查询在外层加锁
    
    id<PLResultSet> result = [database executeQuery: sqlString];
    
//    [self unlock];//数据库查询在外层加锁
    
    return result;
}

+(void) executeUpdateWithoutLockWithSqlString:(NSString *)sqlString
{ 
    NSLog(@"%s %d, sqlString = %@", __FUNCTION__, __LINE__, sqlString);
    BOOL bResult = [database executeUpdate: sqlString];
    
    if (!bResult)
    {
        NSLog(@"executeUpdate: %@", bResult ? @"关闭" : @"Failed");
    }
}

+(BOOL) executeUpdateWithSqlString: (NSString *) sqlString
{
//    NSLog(@"%s %d, sqlString = %@", __FUNCTION__, __LINE__, sqlString);
    
    [self lock];

    BOOL bResult = [database executeUpdate: sqlString];

    [self unlock];

    NSLog(@"executeUpdate: %@", bResult ? @"success" : @"Failed");
    
    return bResult;
}

+(void) executeSqlWithSqlStrings: (NSString *) sqlStrings
{
    NSArray *sqlArray = [sqlStrings componentsSeparatedByString: @";"];
    
    for (NSString *sqlString in sqlArray) 
    {
        sqlString = [sqlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        if ([sqlString length] > 0)
        {
            NSLog(@"--->\n%@", sqlString);
            
            [self executeUpdateWithSqlString: sqlString];
        }
    }
}

CDSQLService.h 单例 放查询方法

#import <Foundation/Foundation.h>
#import "CDSqlManager.h"
@interface CDSQLService : NSObject
+(CDSQLService *)instance;

+(BOOL)update……
+(BOOL)add……
+(BOOL)delete……
+(id)query

CDSQLService.m

#import "CDSQLService.h"

@implementation CDSQLService
static CDSQLService *instance = nil;

+(CDSQLService *)instance{
   @synchronized(self){
       if (!instance) {
           [CDSqlManager openDatabase];
           instance = [[CDSQLService alloc]init];
       }
       
   }
   return instance;
}

-(id)init{
   self = [super init];
   if (self) {
       [self createTablesIfNotExsits];
   }
   return self;
}

-(void)createTablesIfNotExsits{
   // 打开数据库
   //从未装过或者卸载重装或者杀进程在进来的情况
   NSString *sqlString = [NSString stringWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"create_db_table" ofType: @"sql"]
                                                   encoding: NSUTF8StringEncoding
                                                      error: nil];
   
   [CDSqlManager executeSqlWithSqlStrings: sqlString];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,552评论 25 708
  • 需要原文的可以留下邮箱我给你发,这里的文章少了很多图,懒得网上粘啦 1数据库基础 1.1数据库定义 1)数据库(D...
    极简纯粹_阅读 7,536评论 0 46
  • iOS中的数据持久化方式,基本上有以下四种: 属性列表、对象归档、SQLite3和Core Data 1.属性列表...
    Lee坚武阅读 780评论 0 51
  • RecyclerView的下拉刷新需要自己封装,其实是RecyclerView添加头部之后的处理逻辑的编辑。所以我...
    Ayres阅读 404评论 0 2
  • 今天中午舍弃睡午觉的时间,看了部韩国片《嫌疑人》。个人感觉是一部拍得很吸引人的作品,很出色。影片以南韩朴会长被杀展...
    行动派HG阅读 171评论 0 1