欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS开发中使用FMDB来使程序连接SQLite数据库

程序员文章站 2023-02-07 17:11:53
一、简单说明 1.什么是fmdb fmdb是ios平台的sqlite数据库框架 fmdb以oc的方式封装了sqlite的c语言api 2.fmdb的优点 使用起来...

一、简单说明

1.什么是fmdb

fmdb是ios平台的sqlite数据库框架

fmdb以oc的方式封装了sqlite的c语言api

2.fmdb的优点

使用起来更加面向对象,省去了很多麻烦、冗余的c语言代码

对比苹果自带的core data框架,更加轻量级和灵活

提供了多线程安全的数据库操作方法,有效地防止数据混乱

3.fmdb的github地址

https://github.com/ccgus/fmdb

 

二、核心类

fmdb有三个主要的类

(1)fmdatabase

一个fmdatabase对象就代表一个单独的sqlite数据库

用来执行sql语句

(2)fmresultset

使用fmdatabase执行查询后的结果集

(3)fmdatabasequeue

用于在多线程中执行多个查询或更新,它是线程安全的

 

三、打开数据库

通过指定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"];

}


 
六、代码示例

1.新建一个项目,导入libsqlite3库,并在项目中包含主头文件

iOS开发中使用FMDB来使程序连接SQLite数据库

2.下载第三方框架fmdb

iOS开发中使用FMDB来使程序连接SQLite数据库

3.示例代码

  yyviewcontroller.m文件

复制代码 代码如下:

//
//  yyviewcontroller.m
//  04-fmdb基本使用
//
//  created by apple on 14-7-27.
//  copyright (c) 2014年 wendingding. all rights reserved.
//

#import "yyviewcontroller.h"
#import "fmdb.h"

@interface yyviewcontroller ()
@property(nonatomic,strong)fmdatabase *db;
@end

@implementation yyviewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //1.获得数据库文件的路径
    nsstring *doc=[nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) lastobject];
    nsstring *filename=[doc stringbyappendingpathcomponent:@"student.sqlite"];
   
    //2.获得数据库
    fmdatabase *db=[fmdatabase databasewithpath:filename];
   
    //3.打开数据库
    if ([db open]) {
        //4.创表
        bool result=[db executeupdate:@"create table if not exists t_student (id integer primary key autoincrement, name text not null, age integer not null);"];
        if (result) {
            nslog(@"创表成功");
        }else
        {
            nslog(@"创表失败");
        }
    }
    self.db=db;

}

-(void)touchesbegan:(nsset *)touches withevent:(uievent *)event
{
    [self delete];
    [self insert];
    [self query];
}

//插入数据
-(void)insert
{
    for (int i = 0; i<10; i++) {
        nsstring *name = [nsstring stringwithformat:@"jack-%d", arc4random_uniform(100)];
        // executeupdate : 不确定的参数用?来占位
        [self.db executeupdate:@"insert into t_student (name, age) values (?, ?);", name, @(arc4random_uniform(40))];
        //        [self.db executeupdate:@"insert into t_student (name, age) values (?, ?);" withargumentsinarray:@[name, @(arc4random_uniform(40))]];
       
        // executeupdatewithformat : 不确定的参数用%@、%d等来占位
        //        [self.db executeupdatewithformat:@"insert into t_student (name, age) values (%@, %d);", name, arc4random_uniform(40)];
    }
}

//删除数据
-(void)delete
{
    //    [self.db executeupdate:@"delete from t_student;"];
    [self.db executeupdate:@"drop table if exists t_student;"];
    [self.db executeupdate:@"create table if not exists t_student (id integer primary key autoincrement, name text not null, age integer not null);"];
}

//查询
- (void)query
{
    // 1.执行查询语句
    fmresultset *resultset = [self.db executequery:@"select * from t_student"];
   
    // 2.遍历结果
    while ([resultset next]) {
        int id = [resultset intforcolumn:@"id"];
        nsstring *name = [resultset stringforcolumn:@"name"];
        int age = [resultset intforcolumn:@"age"];
        nslog(@"%d %@ %d", id, name, age);
    }
}

@end


打印查看结果:

iOS开发中使用FMDB来使程序连接SQLite数据库

提示:

如果id设置为逐渐,且设置为自动增长的话,那么把表中的数据删除后,重新插入新的数据,id的编号不是从0开始,而是接着之前的id进行编号。

注意:

  不要写成下面的形式,不要加'',直接使用%@,它会自动认为这是一个字符串。

iOS开发中使用FMDB来使程序连接SQLite数据库

七、fmdb数据库队列
1.代码示例

(1).需要先导入fmdb框架和头文件,由于该框架依赖于libsqlite库,所以还应该导入该库。

iOS开发中使用FMDB来使程序连接SQLite数据库

(2).代码如下:

复制代码 代码如下:

//
//  yyviewcontroller.m
//  05-fmdb数据库队列
//
//  created by apple on 14-7-28.
//  copyright (c) 2014年 wendingding. all rights reserved.
//

#import "yyviewcontroller.h"
#import "fmdb.h"

@interface yyviewcontroller ()
@property(nonatomic,strong)fmdatabasequeue *queue;
@end

@implementation yyviewcontroller

- (void)viewdidload
{
    [super viewdidload];
   
    //1.获得数据库文件的路径
    nsstring *doc=[nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) lastobject];
    nsstring *filename=[doc stringbyappendingpathcomponent:@"person.sqlite"];
   
    //2.获得数据库队列
    fmdatabasequeue *queue=[fmdatabasequeue databasequeuewithpath:filename];
//    fmdatabase *db=[fmdatabase databasewithpath:filename];
   
    //3.打开数据库
    [queue indatabase:^(fmdatabase *db) {
         bool result=[db executeupdate:@"create table if not exists t_person (id integer primary key autoincrement, name text not null, age integer not null);"];
        if (result) {
            nslog(@"创表成功");
        }else
        {
            nslog(@"创表失败");
        }
    }];
    self.queue=queue;
   
}

-(void)touchesbegan:(nsset *)touches withevent:(uievent *)event
{
    //插入数据
//    [self.queue indatabase:^(fmdatabase *db) {
//        [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @22];
//    }];
   
    //查询数据
    [self.queue indatabase:^(fmdatabase *db) {
        // 1.执行查询语句
        fmresultset *resultset = [db executequery:@"select * from t_person"];

        // 2.遍历结果
        while ([resultset next]) {
            int id = [resultset intforcolumn:@"id"];
            nsstring *name = [resultset stringforcolumn:@"name"];
            int age = [resultset intforcolumn:@"age"];
            nslog(@"%d %@ %d", id, name, age);
        }
    }];

}

@end


先插入数据,之后查询结果,打印如下:

iOS开发中使用FMDB来使程序连接SQLite数据库

(3).代码说明

有了一个队列对象,它的内部自动就拥有一个数据库对象,且数据库的操作是线程安全的。

iOS开发中使用FMDB来使程序连接SQLite数据库

2.事务
事务,没有事务的话会出现问题。
举例:银行的例子

iOS开发中使用FMDB来使程序连接SQLite数据库

张三和李四账户都有1000块钱,如果张三要转账给李四,需要执行两条sql语句,考虑到安全性,要求这两条鱼具要么全部执行成功,要不全部执行失败。
事务:把多条语句放到同一个事务中,要么全部成功,要不全部失败(如果中途出现问题,那么会自动回滚)。事务的执行具有原子性。
  事务代码处理:
  把多条语句添加到一个事务中去执行:

复制代码 代码如下:

//插入数据
    [self.queue indatabase:^(fmdatabase *db) {
        [db begintransaction];
        [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @22];
        [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @23];
        [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @24];
        [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @25];
        [db commit];
    }];

如果中途出现问题,那么会自动回滚,也可以选择手动回滚。
复制代码 代码如下:

//插入数据
    [self.queue indatabase:^(fmdatabase *db) {
        [db begintransaction];
        [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @22];
        [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @23];
        [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @24];
        [db rollback];
        [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @25];
        [db commit];
    }];

上面的代码。前三条插入语句是作废的。

事务处理的另一种方式:

复制代码 代码如下:

[self.queue intransaction:^(fmdatabase *db, bool *rollback) {
     [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @22];
     [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @23];
     [db executeupdate:@"insert into t_person (name, age) values (?, ?);",@"wendingding", @24];
 }];
说明:先开事务,再开始事务,之后执行block中的代码段,最后提交事务。