0
点赞
收藏
分享

微信扫一扫

iOS开发之FMDB的简单使用

前言

以前使用SQLite十分的麻烦,代码很冗余,所以开发者朋友们一般在实际开发的过程中都是使用的是FMDB这个开元框架,那么下面我们就来了解一下FMDB这个轻量级的框架的简单使用吧.

  • 基本概念:
  • 使用FMDB的优点:
  • 使用FMDB的注意点:
  • FMDB的基本结构
  • 如何打开数据库以及注意点:
 打开数据库: 是通过指定的SQLite数据库文件路径来创建FMDatabase对象的.
         // 打开数据库
         FMDatabase *db = [FMDatabase databaseWithPath:filePath];
         if (![db open]) {
         NSLog(@"打开数据库失败, 直接返回");
         return;
         }
  • 执行更新操作
 6, 执行更新: 在FMDB中,除了查询,所有的操作都得update操作,使用executeUpdate:方法执行更新操作
    [db executeUpdate:@"UPDATE t_student SET age = ? WHERE name = ?;", @20, @"Alex"];
  • 执行查询]
执行查询: 使用executeQuery:方法
 // 查询数据
 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"];
 }
  • FMDatabaseQueue(队列:默认是线程安全的)
FMDatabaseQueue: FMDatabase这个类是线程不安全的,如果多条线程同时访问我
们的数据库,会造成数据紊乱等现象.所以,为了保证我们的线程安全问题, 
FMDB提供了安全便捷的FMDatabaseQueue类.
 FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
  • 关闭数据库
关闭数据库: 直接调用数据库的close方法即可: 
[db close]

下面是使用FMDB的简单实例

  • 使用FMDB的前提准备

  • 设置storyboard



//
//  ViewController.m
//  FMDB的简单使用
//
//  Created by Alex William on 16/8/4.
//  Copyright © 2016年 WeiKa. All rights reserved.
//

/*
 创建数据库和数据表的基本步骤: 
 1, 拼接保存数据库的绝对路径
 2, 通过路径创建数据库
 3, 打开数据库(打开后才能执行SQLite语句)
 */

#import "ViewController.h"


@interface ViewController ()

@property(nonatomic, strong) FMDatabaseQueue *queue;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 获取沙盒的地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    // 拼接数据库的全路径
    NSString *filePath = [path stringByAppendingPathComponent:@"student.sqlite"];
    
    // 打印数据库地址
    NSLog(@"filePath =%@", filePath);
    
    // 创建一个FMDatabaseQueue对象
    // 只要创建了数据库队列对象,FMDB内部就会自动帮我们加载数据库对象
    self.queue = [FMDatabaseQueue databaseQueueWithPath:filePath];
    
    // 执行操作(内部会通过block传递创建好的数据库给我们)
    [self.queue inDatabase:^(FMDatabase *db) {
       
        // 创建表(在FMDB框架中, 增加/删除/修改/创建/销毁等操作都是属于更新)
        BOOL success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, score REAL DEFAULT 1);"];
        
        if (success) {
            
            NSLog(@"创建表成功");
        } else {
            
            NSLog(@"创建表失败");
        }
    }];
}


// 插入
- (IBAction)insertOnClicked:(id)sender {
    
    [self.queue inDatabase:^(FMDatabase *db) {
        
        // 插入数据
        // 在FMDB中可以使用?当做占位符, 但是需要注意: 如果使用问号作为占位符, 以后只能给问号传递对象
        BOOL success = [db executeUpdate:@"INSERT INTO t_student (id, name, score) VALUES (?, ?, ?);",@(1), @"Alex", @(99)];
        
        if (success) {
            
            NSLog(@"插入数据成功");
        } else {
            
            NSLog(@"插入数据失败");
        }
    }];
}

// 删除
- (IBAction)deletedOnClicked:(id)sender {
}

// 修改
- (IBAction)upDateOnCliked:(id)sender {
    
  [self.queue inDeferredTransaction:^(FMDatabase *db, BOOL *rollback) {
     
     BOOL success = [db executeUpdateWithFormat:@"UPDATE t_student SET score = 100 WHERE name = 'Alex';"];
      if (success) {
          
          NSLog(@"修改成功");
      } else
      {
          NSLog(@"修改失败");
      }
  }];
}

// 查询
- (IBAction)queryOnClicked:(id)sender {
    
    [self.queue inDatabase:^(FMDatabase *db) {
       
        // 在FMDB框架中除了查询所有的操作都是update操作, 而查询操作使用的是executeQuery操作
        // 在使用查询方法时,需要用到FDMB中的结果集FMResultSet
        FMResultSet *results = [db executeQuery:@"SELECT id, name, score FROM t_student;"];
        
        
        // next方法如果返回的是YES,说明有数据可查, 如果返回NO说明查询失败
        while ([results next]) {
            
            // 有两种方式获取到数据库中的数据
            /*
             方式一:
             int ID = [results intForColumnIndex:0];
             NSString *name = [results stringForColumnIndex:1];
             double score = [results doubleForColumnIndex:2];
             NSLog(@"ID = %d, name = %@, score = %f", ID, name, score);
             */
            
            // 方式二:
            int ID = [results intForColumn:@"id"];
            NSString *name = [results stringForColumn:@"name"];
            double score = [results doubleForColumn:@"score"];
            NSLog(@"ID = %d, name = %@, score = %f", ID, name, score);
        }
    }];
    
}

@end
举报

相关推荐

0 条评论