FMDB是一种第三方的开源库,FMDB就是对SQLite的API进行了封装,加上了面向对象的思想,让我们不必使用繁琐的C语言API函数,比起直接操作SQLite更加方便。

    FMDB优点:
    1.使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码
    2.对比苹果自带的CoreData框架,更加轻量级和灵活
    3.提供多线程安全,有效地防止数据混乱,原来的SQLite不是线程安全

    FMDB缺点:

    因为是OC语言封装的,失去了SQLite原来的跨平台性

    我们要使用FMDB需要的步骤:

    1.项目中添加libsqlite3库的依赖
    2.导入FMDB源码:
    3.下载FMDB的源代码,将代码文件拖入工程
    4.#import导入FMDB的头文件"FMDatabase.h"

    使用FMDB前,需要先了解下3个主要类:

    1.FMDatabase : 一个单一的SQLite数据库,用于执行SQL语句。
    2.FMResultSet :执行查询一个FMDatabase结果集。
    3.FMDatabaseQueue :在多个线程来执行查询和更新时会使用这个类。

    一般的FMDB数据库操作有:
    1.创建数据库
    2.打开数据库、关闭数据库
    3.执行更新(增加、删除、修改)的SQL语句
    4.执行查询的SQL语句

一、打开数据库

通过指定SQLite数据库文件路径来创建FMDatabase对象

FMDatabase *db = [FMDatabase databaseWithPath:path];

 if (![db open]) {

 NSLog(@"数据库打开失败!");

 }




文件路径有三种情况

(1)具体文件路径

  如果不存在会自动创建



(2)空字符串@""

  会在临时目录创建一个空的数据库

  当FMDatabase连接关闭时,数据库文件也被删除



(3)nil

  会创建一个内存中临时数据库,当FMDatabase连接关闭时,数据库会被销毁



二、执行更新

在FMDB中,除查询以外的所有操作,都称为“更新”

create、drop、insert、update、delete等



使用executeUpdate:方法执行更新

- (BOOL)executeUpdate:(NSString*)sql, ...

 - (BOOL)executeUpdateWithFormat:(NSString*)format, ...

 - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments




示例

[db executeUpdate:@"UPDATE t_student SET age = ? WHERE name = ?;", @20, @"Jack"]




三、执行查询

查询方法

- (FMResultSet *)executeQuery:(NSString*)sql, ...

 - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ...

 - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments




示例

// 查询数据

 FMResultSet *rs = [db executeQuery:@"SELECT * FROM t_student"];



 // 遍历结果集

 while ([rs next]) {

 NSString *name = [rs stringForColumn:@"name"];

 int age = [rs intForColumn:@"age"];

 double score = [rs doubleForColumn:@"score"];

 }



代码示例:

//MARK:创建本地数据库
- (void)CreateDatabase
{
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"liantongzhanting.db"];
    FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];
    
    if ([db open]) {
        
        NSString*createTable=@"create table firstcontentlist_tb (id integer primary key autoincrement,contentName text,fileName text,veision text);"
        "create table contentlist_tb (id integer primary key autoincrement,contentId text,contentName text,contentNo text, fileName text, filePath text,veision text);"
        "create table userinfo_tb(id integer primary key autoincrement, areaId text,email text,password text,status text,tel text,userId text,username text);"
        "create table collect_tb (id integer primary key autoincrement, collectImage text,filePath text,contentID text,collectTitle text,collectDesc text,collectText text,tel text,collectTime text,state text,collectType text);"
        "create table addcollect_tb (id integer primary key autoincrement, imagePath text,url text);"
        "create table loginfo_tb (id integer primary key autoincrement, tel text,resultDetail text,showroomName text,optDetail text,objectId text,resultCode text,optCode text,optTime text,logdel text);"
        "create table orderinfo_tb (id integer primary key autoincrement, orderTime text,customerCompany text,customerIndustry text,customerName text,customerDepartment text,customerJob text,customerPhone text,customerMail text,id text,state text);";
        
        BOOL result=[db executeStatements:createTable];
        
        if (result)
        {
            NSLog(@"创表成功");
        }else
        {
            NSLog(@"创表失败");
        }
    }
    
    [db close];
}

增加数据:

//MARK:插入下载内容列表
-(void)insertContentlist:(NSMutableArray*)data
{
    [queue inDatabase:^(FMDatabase *db) {
        //打开数据库
        if ([db open]) {
            [db executeUpdate:[NSString stringWithFormat:@"delete from contentlist_tb"]];
        }
    }];
    if(data==nil||data.count<=0)
    {
        return;
    }
    NSString*insertContentSql=@"insert into contentlist_tb(contentId ,contentName ,contentNo,fileName,filePath ,veision) values (?,?,?,?,?,?)";
    [queue inDatabase:^(FMDatabase *db) {
        //打开数据库
        if ([db open]) {
            db.beginTransaction;
            for(int i=0;i<data.count;i++)
            {
                NSDictionary* contentData=[data objectAtIndex:i];
                NSString*contentId=[contentData objectForKey:@"contentId"];
                NSString*contentName=[contentData objectForKey:@"contentName"];
                
                NSString*contentNo=[contentData objectForKey:@"contentNo"];
                
                NSString*fileName=[contentData objectForKey:@"fileName"];
                NSString*filePath=[contentData objectForKey:@"filePath"];
                NSString*veision=[contentData objectForKey:@"veision"];
                
                NSArray*contentValues= [[NSArray alloc] initWithObjects:contentId,contentName,contentNo,fileName,filePath,veision,nil];
                
                [db executeUpdate:insertContentSql withArgumentsInArray:contentValues];
                
            }
            
            
        }
        db.commit;
    }];
    
}



删除数据:

//操作收藏数据库,删除
    [queue inDatabase:^(FMDatabase *db) {
        //打开数据库
        if ([db open]) {
            [db executeUpdate:[NSString stringWithFormat:@"delete from collect_tb where id='%@'",idStr]];
            
        }
    }];



更新数据:

FMDatabaseQueue* queue=[FMDatabaseQueue getSharedDatabaseQueue];
                [queue inDatabase:^(FMDatabase *db) {
                    //打开数据库
                    if ([db open]) {
                        [db executeUpdate:@"UPDATE loginfo_tb SET logdel = ? WHERE optTime = ?",logdel,optTime];
                        NSLog(@"operationtime=======%@",optTime);
        
                    }
                }];

查询数据:

//根据filename查询version
            arguments = [NSMutableArray array];
            [queue inDatabase:^(FMDatabase *db) {
                if ([db open]) {
                    
                    FMResultSet *rs = [db executeQuery:[NSString stringWithFormat:@"SELECT * FROM contentlist_tb where fileName='%@'",filename]];
                    while ([rs next]) {
                        
                        [arguments addObject:[rs resultDictionary]];
                        
                    }
                    [rs close];
                    
                }
            }];

[queue inDatabase:^(FMDatabase *db) {
        if ([db open]) {
            FMResultSet *rs = [db executeQuery:@"SELECT * FROM contentlist_tb"];
            arguments = [NSMutableArray array];
            
            while ([rs next]) {
                
                [arguments addObject: [rs resultDictionary]];
            }
            [rs close];
            
        }
    }];



以上就是FMDB的基本使用方法和几种基本的操作数据库的方法,用起来简单易懂,十分方便,大家尽可尝试。