fmdb的使用教程

  最近开始搭建项目的数据库,所以详细的看了一些关于数据库的知识,互相学习~~。

  iOS中数据存储的方式有以下几种:

  1.Plist:智能存储系统自带的数据类型.字典,数组,string,这些。

    2.Perference:偏好设置,NSUserDefaults,从根本上就是一个plist文件,和plist类似,只不过为了方便开发者统一。

  3.Nscoding:主要用来存储自定义的数据类型,需要重写归档,解档方法

  4.SQlite3:ios的轻型的嵌入式数据库,存储一些大批量的数据。

  数据库表的操作:

  DDL:数据定义语句 。主要是创建,删除表。

CREATE TABLE IF NOT EXISTS t_student(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER);
CREATE TABLE IF NOT EXISTS t_student(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS t_student(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER);
CREATE TABLE IF NOT EXISTS t_student(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER DEFAULT 1);

  DML:数据库操作语句 。主要是数据库表内的增,删,改

/*插入数据*/
 INSERT INTO t_student(age, score, name) VALUES ('28', 100, 'jonathan');
 INSERT INTO t_student(name, age) VALUES ('lee', '28');
 INSERT INTO t_student(score) VALUES (100);
/*删除数据*/
DELETE FROM t_student; //删除所有数据
DELETE FROM t_student WHERE name = 'cnw' age = 20;
DELETE FROM t_student WHERE name = 'qlt' and age >26 and score < 80;
/*修改指定数据*/
UPDATE t_student SET name = 'MM' WHERE age = 10;
UPDATE t_student SET name = 'WW' WHERE age is 7;
UPDATE t_student SET name = 'XXOO' WHERE age < 20;
UPDATE t_student SET name = 'NNMM' WHERE age < 50 and score > 10;

  DQL:数据查询语句 ,zhu要是查询

/*查询*/
SELECT name, age, score FROM t_student;
SELECT * FROM t_student;
/*分页*/
SELECT * FROM t_student ORDER BY id ASC LIMIT 20, 10;
// id 默认升序排列,跳过20条数据取10条

 基础解决了,到了重点了~~

 Fmdb的使用:

 fmdatabase:提供sqlite数据库的类,用于执行sql语句

 fmresultset:用于查询数据,除了删除都是查询

 fmdatabaequeue 在多线程下查询和更新数据库用到的类,避免线程阻塞。

  CREATE TABLE

// 0.获取沙盒地址
 NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
 // 拼接路径
 NSString * filePath = [path stringByAppendingPathComponent:@"person.sqlite"];

 // 1. 加载数据库对象
 self.db = [FMDatabase databaseWithPath:filePath];
 // 2.打开数据库
 if ([self.db open]) {
     // 创建表(在FMDB框架中,增删改查销毁都统称为更新)
   BOOL success = [self.db executeUpdate:@"create table if not exists t_person (id integer primary key autoincrement,name text not null,age integer,weight real default 120);"];
     if (success) {
         NSLog(@"创表成功");
     }else{
         NSLog(@"创表失败");
     }
 }else{
     NSLog(@"打开失败");
 }

 INSERT DATA

- (IBAction)insert {
    // 在FMDB中可以用?当做占位符,但是:如果使用占位符,以后只能给占位符传递对象
  BOOL success = [self.db executeUpdate:@"insert into t_person(name ,age,weight) values(?,?,?);",@"QLT",@"25",@"108"];
    if (success) {
        NSLog(@"插入成功");
    }else{
        NSLog(@"插入失败");
    }
}

DELETE DATA

- (IBAction)deleate {
    BOOL success = [self.db executeUpdate:@"delete from t_person"];
    if (success) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }

}

UPDATE DATA

BOOL success = [self.db executeUpdate:@"update t_person set name = 'qlt' where weight = 108"];
    if (success) {
        NSLog(@"修改成功");
    }else{
        NSLog(@"修改失败");
    }

SELECT DATA

// FMResultSet结果集
    FMResultSet * set = [self.db executeQuery:@"select id,name,age,weight from t_person;"];
    if ([set next]) { // next 返回yes说明有数据
        int ID = [set intForColumnIndex:0];
        NSString * name = [set stringForColumnIndex:1];
        double weight = [set doubleForColumnIndex:3];
        NSLog(@"id = %d,name = %@,weight = %.1f",ID,name,weight);
    }else{
        NSLog(@"查询出错");
    }

FMDatabaseQueue 的基本用法

CREATE TABLE

 // 1.创建一个FMDatabaseQueue对象
    // 只要创建数据库队列对象, FMDB内部就会自动给我们加载数据库对象
    self.queue = [FMDatabaseQueue databaseQueueWithPath:filePath];

    //2 .执行操作
    // 会通过block传递队列中创建好的数据库给我们
    [self.queue inDatabase:^(FMDatabase *db) {
        // 编写需要执行的代码
        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(@"创建表失败");
        }
    }];

UPDATE

- (IBAction)update {

    [self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        [db executeUpdate:@"UPDATE t_person SET weight = 1500 WHERE name = 'zs';"];

        NSArray *array = @[@"abc"];
        array[1];

        [db executeUpdate:@"UPDATE t_person SET weight = 500 WHERE name = 'ls';"];
    }];

}

SELECT

[self.queue inDatabase:^(FMDatabase *db) {
        // FMResultSet结果集, 结果集其实和tablevivew很像
        FMResultSet *set = [db executeQuery:@"SELECT id, name, score FROM t_student;"];
        while ([set next]) { // next方法返回yes代表有数据可取
            int ID = [set intForColumnIndex:0];
            //        NSString *name = [set stringForColumnIndex:1];
            NSString *name = [set stringForColumn:@"name"]; // 根据字段名称取出对应的值
            double score = [set doubleForColumnIndex:2];
            NSLog(@"%d %@ %.1f", ID, name, score);
        }
    }];

有什么遗漏,请于评论相告,thanks

最后感谢Nbm的帮助,此是原文http://www.jianshu.com/p/66a6cbb4330c

原文地址:https://www.cnblogs.com/gaozhang12345/p/6668984.html