天天看点

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、数据库执行语句

查询:

增,删,改: