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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM