美文网首页
FMDB的使用

FMDB的使用

作者: 旧雨伞时 | 来源:发表于2016-08-08 15:28 被阅读0次

    iOS中原生的SQLite API在使用上相当不友好,在使用时,非常不便。于是,就出现了一系列将SQLite API进行封装的库,例如FMDB、PlausibleDatabase、sqlitepersistentobjects等,FMDB (https://github.com/ccgus/fmdb) 是一款简洁、易用的封装库.

    在FMDB下载文件后,工程中必须导入如下文件,并使用 libsqlite3.dylib 依赖包。


    fmdb.png

    FMDB常用类:
    FMDatabase: 一个单一的SQLite数据库, 用于执行SQL语句.
    FMResultSet: 执行查询一个FMDataBase结果集, 这个和安卓的Cursor类似.
    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"];
    
    }
    

    四. 代码示例:

    - (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);
      }
    }
    

    相关文章

      网友评论

          本文标题:FMDB的使用

          本文链接:https://www.haomeiwen.com/subject/vbrrsttx.html