天天看點

SQLite庫FMDB的基本使用

一、什麼是FMDB ?

SQLite的API是C語言寫的,使用起來比較麻煩。是以就有了SQLite的第三方庫。FMDB以OC的方式封裝了SQLite的C語言API ( application programming interface 應用程式接口)。

二、FMDB的優點

使用起來更加面向對象,省去了很多麻煩、備援的C語言代碼

對比蘋果自帶的Core Data架構,更加輕量級和靈活 ,提供了多線程安全的資料庫操作方法,有效地防止資料混亂。

FMDB的github位址

https://github.com/ccgus/fmdb

三、FMDB有三個主要的類

FMDatabase

一個FMDatabase對象就代表一個單獨的SQLite資料庫

用來執行SQL語句

FMResultSet

使用FMDatabase執行查詢後的結果集

FMDatabaseQueue

用于在多線程中執行多個查詢或更新,它是線程安全的

四、基本使用流程

1、首先在工程中導入FMDB庫。

2、然後封裝一個操作資料庫的類。

3、在類的.m中實作方法

#import "DataBase.h"
static FMDatabase *_db; //定義一個靜态全局變量

@implementation DataBase
// 建立資料庫和表
+(void)createDataBaseAndCreateTable{ 

    if (_db==nil) { //判斷資料庫是否存在 
        _db = [[FMDatabase alloc]initWithPath:[NSString stringWithFormat:@"%@/Documents/data.sqlite",NSHomeDirectory()]]; //如果不存在建立
        [_db open]; //打開資料庫

        NSString *createSql = @"create table  if not exists people(people_ID integer primary key autoincrement,name text,phone text)";//建立資料庫people表

        [_db executeUpdate:createSql];//執行語句
        [_db close]; //關閉資料庫

    }


}
           

查詢最大的ID

+(NSInteger)getMaxID{

     NSString *select  = @"select  MAX(people_ID) from people";
    [_db open];
FMResultSet *set = [_db executeQuery:select];
    [set next];
    NSInteger   max = [set intForColumnIndex:];
    [set close];
    [_db close];
    return max;
}
           

4、資料庫執行語句

查詢:

增,删,改:

繼續閱讀