IOS数据持久化存储之SQLite3第三方库FMDB的使用

2024-08-22 18:58

本文主要是介绍IOS数据持久化存储之SQLite3第三方库FMDB的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

SQLite是一种小型的轻量级的关系型数据库,在移动设备上使用是非常好的选择,无论是Android还是IOS,都内置了SQLite数据库,现在的版本都是SQLite3。在IOS中使用SQLite如果使用SDK提供的方法,特别麻烦也不利于理解和使用,在之前的http://blog.csdn.net/tangren03/article/details/7781930文章中就是使用IOS的SDK自带的SQLite API来使用数据库,感觉使用很不方便,今天就讲讲一个针对IOS的SQlite API封装的第三方库FMDB,FMDB对SDK中的API做了一层封装,使之使用OC来访问,使用方便而且更熟悉。FMDB的下载地址https://github.com/ccgus/fmdb


FMDB主要涉及两个类,FMDatabase和FMResultSet,前者类似于Android中的SQLiteOpenHelper或SQLiteDatabase,FMResultSet类似于Android中的Cursor,用来存储结果集。


FMDB常用类:

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

创建数据库:

[cpp]  view plain copy print ?
  1. db = [FMDatabase databaseWithPath:database_path];  

         1、当数据库文件不存在时,fmdb会自己创建一个。

         2、 如果你传入的参数是空串:@"" ,则fmdb会在临时文件目录下创建这个数据库,数据库断开连接时,数据库文件被删除。

         3、如果你传入的参数是 NULL,则它会建立一个在内存中的数据库,数据库断开连接时,数据库文件被删除。


打开数据库:

[cpp]  view plain copy print ?
  1. [db open]  
返回BOOL型。

关闭数据库:

[cpp]  view plain copy print ?
  1. [db close]  

数据库增删改等操作:

除了查询操作,FMDB数据库操作都执行executeUpdate方法,这个方法返回BOOL型

看一下例子:

例子一

创建表:

[cpp]  view plain copy print ?
  1. if ([db open]) {  
  2.         NSString *sqlCreateTable =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' INTEGER, '%@' TEXT)",TABLENAME,ID,NAME,AGE,ADDRESS];  
  3.         BOOL res = [db executeUpdate:sqlCreateTable];  
  4.         if (!res) {  
  5.             NSLog(@"error when creating db table");  
  6.         } else {  
  7.             NSLog(@"success to creating db table");  
  8.         }  
  9.         [db close];  
  10.   
  11.     }  


添加数据:

[cpp]  view plain copy print ?
  1. if ([db open]) {  
  2.        NSString *insertSql1= [NSString stringWithFormat:  
  3.                               @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",  
  4.                               TABLENAME, NAME, AGE, ADDRESS, @"张三", @"13", @"济南"];  
  5.        BOOL res = [db executeUpdate:insertSql1];  
  6.        NSString *insertSql2 = [NSString stringWithFormat:  
  7.                                @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",  
  8.                                TABLENAME, NAME, AGE, ADDRESS, @"李四", @"12", @"济南"];  
  9.        BOOL res2 = [db executeUpdate:insertSql2];  
  10.          
  11.        if (!res) {  
  12.            NSLog(@"error when insert db table");  
  13.        } else {  
  14.            NSLog(@"success to insert db table");  
  15.        }  
  16.        [db close];  
  17.   
  18.    }  


修改数据:

[cpp]  view plain copy print ?
  1. if ([db open]) {  
  2.         NSString *updateSql = [NSString stringWithFormat:  
  3.                                @"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'",  
  4.                                TABLENAME,   AGE,  @"15" ,AGE,  @"13"];  
  5.         BOOL res = [db executeUpdate:updateSql];  
  6.         if (!res) {  
  7.             NSLog(@"error when update db table");  
  8.         } else {  
  9.             NSLog(@"success to update db table");  
  10.         }  
  11.         [db close];  
  12.   
  13.     }  


删除数据:

[cpp]  view plain copy print ?
  1. if ([db open]) {  
  2.           
  3.         NSString *deleteSql = [NSString stringWithFormat:  
  4.                                @"delete from %@ where %@ = '%@'",  
  5.                                TABLENAME, NAME, @"张三"];  
  6.         BOOL res = [db executeUpdate:deleteSql];  
  7.           
  8.         if (!res) {  
  9.             NSLog(@"error when delete db table");  
  10.         } else {  
  11.             NSLog(@"success to delete db table");  
  12.         }  
  13.         [db close];  
  14.   
  15.     }  


数据库查询操作:

查询操作使用了executeQuery,并涉及到FMResultSet。

[cpp]  view plain copy print ?
  1. if ([db open]) {  
  2.         NSString * sql = [NSString stringWithFormat:  
  3.                           @"SELECT * FROM %@",TABLENAME];  
  4.         FMResultSet * rs = [db executeQuery:sql];  
  5.         while ([rs next]) {  
  6.             int Id = [rs intForColumn:ID];  
  7.             NSString * name = [rs stringForColumn:NAME];  
  8.             NSString * age = [rs stringForColumn:AGE];  
  9.             NSString * address = [rs stringForColumn:ADDRESS];  
  10.             NSLog(@"id = %d, name = %@, age = %@  address = %@", Id, name, age, address);  
  11.         }  
  12.         [db close];  
  13.     }  


FMDB的FMResultSet提供了多个方法来获取不同类型的数据:


数据库多线程操作:

        如果应用中使用了多线程操作数据库,那么就需要使用FMDatabaseQueue来保证线程安全了。 应用中不可在多个线程中共同使用一个FMDatabase对象操作数据库,这样会引起数据库数据混乱。 为了多线程操作数据库安全,FMDB使用了FMDatabaseQueue,使用FMDatabaseQueue很简单,首先用一个数据库文件地址来初使化FMDatabaseQueue,然后就可以将一个闭包(block)传入inDatabase方法中。 在闭包中操作数据库,而不直接参与FMDatabase的管理。

[cpp]  view plain copy print ?
  1. FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:database_path];  
  2.    dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);  
  3.    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);  
  4.      
  5.    dispatch_async(q1, ^{  
  6.        for (int i = 0; i < 50; ++i) {  
  7.            [queue inDatabase:^(FMDatabase *db2) {  
  8.                  
  9.                NSString *insertSql1= [NSString stringWithFormat:  
  10.                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",  
  11.                                       TABLENAME, NAME, AGE, ADDRESS];  
  12.                  
  13.                NSString * name = [NSString stringWithFormat:@"jack %d", i];  
  14.                NSString * age = [NSString stringWithFormat:@"%d", 10+i];  
  15.                  
  16.                  
  17.                BOOL res = [db2 executeUpdate:insertSql1, name, age,@"济南"];  
  18.                if (!res) {  
  19.                    NSLog(@"error to inster data: %@", name);  
  20.                } else {  
  21.                    NSLog(@"succ to inster data: %@", name);  
  22.                }  
  23.            }];  
  24.        }  
  25.    });  
  26.      
  27.    dispatch_async(q2, ^{  
  28.        for (int i = 0; i < 50; ++i) {  
  29.            [queue inDatabase:^(FMDatabase *db2) {  
  30.                NSString *insertSql2= [NSString stringWithFormat:  
  31.                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",  
  32.                                       TABLENAME, NAME, AGE, ADDRESS];  
  33.                  
  34.                NSString * name = [NSString stringWithFormat:@"lilei %d", i];  
  35.                NSString * age = [NSString stringWithFormat:@"%d", 10+i];  
  36.                  
  37.                BOOL res = [db2 executeUpdate:insertSql2, name, age,@"北京"];  
  38.                if (!res) {  
  39.                    NSLog(@"error to inster data: %@", name);  
  40.                } else {  
  41.                    NSLog(@"succ to inster data: %@", name);  
  42.                }  
  43.            }];  
  44.        }  
  45.    });  

例子二:


下载完FMDB源码后把文件拖到工程中,并导入SQLite支持库,工程目录如下:

                                                    

然后就是这个Demo的完整截图:

                                            

然后就来看看如何操作FMDB:

[cpp]  view plain copy
  1. //点击按钮后执行保存到数据库的操作  
  2. - (IBAction)saveButtonClicked:(id)sender {  
  3.     //获取Document文件夹下的数据库文件,没有则创建  
  4.     NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];  
  5.     NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];  
  6.       
  7.     //获取数据库并打开  
  8.     FMDatabase *database  = [FMDatabase databaseWithPath:dbPath];  
  9.     if (![database open]) {  
  10.         NSLog(@"Open database failed");  
  11.         return;  
  12.     }  
  13.       
  14.     //创建表(FMDB中只有update和query操作,出了查询其他都是update操作)
  15.     //2014.3.6 sfx 修改:创建表时应该先查看表是否已经存在,如果不存在再创建  
  16.    FMResultSet *rs = [database executeQuery:@"select count(*) as 'count' from sqlite_master where type = 'table' and name = ?",@"user"];

        if ([rs next])

        {

            NSInteger count = [rs intForColumn:@"count"];

            NSLog(@"The table count: %d",count);

            if (count == 1) {

                NSLog(@"user table is existed.");

                return;

            }

            NSLog(@"user table is not existed.");

            [database executeUpdate:@"create table user (name text,gender text,age integer)"];      

        }      

  17.     //插入数据  
  18.     BOOL insert = [database executeUpdate:@"insert into user values (?,?,?)",nameTextField.text,genderTextField.text,ageTextField.text];  
  19.       
  20.     if (insert) {  
  21.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];  
  22.         [alert show];  
  23.         [alert release];  
  24.     }  
  25.       
  26.     [database close];  
  27. }  

操作成功后弹出提示框:

                                             

[cpp]  view plain copy
  1. //点击按钮后执行查询操作  
  2. - (IBAction)queryButtonTapped:(id)sender {  
  3.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  4.     NSString *documentPath = [paths objectAtIndex:0];  
  5.     NSString *dbPath = [documentPath stringByAppendingPathComponent:@"user.db"];  
  6.       
  7.     FMDatabase *database = [FMDatabase databaseWithPath:dbPath];  
  8.     if (![database open]) {  
  9.         return;  
  10.     }  
  11.       
  12.     //不需要像Android中那样关闭Cursor关闭FMResultSet,因为相关的数据库关闭时,FMResultSet也会被自动关闭  
  13.     FMResultSet *resultSet = [database executeQuery:@"select * from user"];  
  14.     while ([resultSet next]) {  
  15.         NSString *name = [resultSet stringForColumn:@"name"];  
  16.         NSString *gender = [resultSet stringForColumn:@"gender"];  
  17.         int age = [resultSet intForColumn:@"age"];  
  18.         NSLog(@"Name:%@,Gender:%@,Age:%d",name,gender,age);  
  19.           
  20.     }  
  21.       
  22.     [database close];  
  23.     //这里也不需要release  
  24. //    [database release];  
  25. }  

FMResultSet还支持以下方式获取值:

  • intForColumn:
  • longForColumn:
  • longLongIntForColumn:
  • boolForColumn:
  • doubleForColumn:
  • stringForColumn:
  • dateForColumn:
  • dataForColumn:
  • dataNoCopyForColumn:
  • UTF8StringForColumnIndex:
  • objectForColumn:

[cpp]  view plain copy
  1. //执行条件查询操作  
  2. - (IBAction)queryByConditionBtnTapped:(id)sender {  
  3.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  4.     NSString *docPath = [paths objectAtIndex:0];  
  5.     NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];  
  6.       
  7.     FMDatabase *database = [FMDatabase databaseWithPath:dbPath];  
  8.     if (![database open]) {  
  9.         return;  
  10.     }  
  11.       
  12.     FMResultSet *resultSet = [database executeQuery:@"select * from user where name = ?",@"Ryan"];  
  13.     while ([resultSet next]) {  
  14.         NSString *name = [resultSet stringForColumn:@"name"];  
  15.         NSString *gender = [resultSet stringForColumn:@"gender"];  
  16.         int age = [resultSet intForColumn:@"age"];  
  17.         NSLog(@"Name:%@,Gender:%@,Age:%d",name,gender,age);  
  18.     }  
  19.       
  20.     [database close];  
  21. }  


[cpp]  view plain copy
  1. //执行更新操作  
  2. - (IBAction)updateBtnTapped:(id)sender {  
  3.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  4.     NSString *docPath = [paths objectAtIndex:0];  
  5.     NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];  
  6.       
  7.     FMDatabase *database = [FMDatabase databaseWithPath:dbPath];  
  8.     if (![database open]) {  
  9.         return;  
  10.     }  
  11.       
  12.     //参数必须是NSObject的子类,int,double,bool这种基本类型,需要封装成对应的包装类才可以  
  13.     BOOL update = [database executeUpdate:@"update user set name = ? where age = ?",@"RyanTang",[NSNumber numberWithInt:24]];  
  14.   
  15.     if(update){  
  16.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"更新成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];  
  17.         [alert show];  
  18.         [alert release];  
  19.     }  
  20.   
  21.     [database close];  
  22. }  

                                       

[cpp]  view plain copy
  1. //执行删除操作  
  2. - (IBAction)deleteBtnTapped:(id)sender {  
  3.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  4.     NSString *docPath = [paths objectAtIndex:0];  
  5.     NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];  
  6.       
  7.     FMDatabase *database = [FMDatabase databaseWithPath:dbPath];  
  8.     if (![database open]) {  
  9.         return;  
  10.     }  
  11.   
  12.     BOOL delete = [database executeUpdate:@"delete from user where name = ?",@"Tang"];  
  13.     if (delete) {  
  14.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"删除成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];  
  15.         [alert show];  
  16.         [alert release];  
  17.   
  18.     }  
  19.       
  20.     [database close];  
  21. }  

                                       

如果我们的app需要多线程操作数据库,那么就需要使用FMDatabaseQueue来保证线程安全了。切记不能在多个线程中共同一个FMDatabase对象并且在多个线程中同时使用,这个类本身不是线程安全的,这样使用会造成数据混乱等问题。

     使用FMDatabaseQueue很简单,首先用一个数据库文件地址来初使化FMDatabaseQueue,然后就可以将一个闭包(block)传入inDatabase方法中。在闭包中操作数据库,而不直接参与FMDatabase的管理。

 

[cpp]  view plain copy
  1. -(void)executeDBOperation  
  2. {  
  3.     //获取Document文件夹下的数据库文件,没有则创建  
  4.     NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];  
  5.     NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];  
  6.       
  7.     FMDatabaseQueue *databaseQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath];  
  8.     [databaseQueue inDatabase:^(FMDatabase *db){  
  9.     [db executeUpdate:@"insert into user values (?,?,?)",@"Ren",@"Male",[NSNumber numberWithInt:20]];  
  10.     }];  
  11.     [databaseQueue close];  
  12. }  


经过修改后的工程源码:传送门在此



这篇关于IOS数据持久化存储之SQLite3第三方库FMDB的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1097119

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没