- FMDB是iOS平臺(tái)的SQLite數(shù)據(jù)庫框架
FMDB以O(shè)C的方式封裝了SQLite的C語言API
-
FMDB的優(yōu)點(diǎn)
- 使用起來更加面向?qū)ο?,省去了很多麻煩、冗余的C語言代碼
- 提供了多線程安全的數(shù)據(jù)庫操作方法,有效地防止數(shù)據(jù)混亂
核心類-三個(gè)主要的類
- FMDatabase
一個(gè)FMDatabase對象就代表一個(gè)單獨(dú)的SQLite數(shù)據(jù)庫,用來執(zhí)行SQL語句
FMResultSet
使用FMDatabase執(zhí)行查詢后的結(jié)果集FMDatabaseQueue
用于在多線程中執(zhí)行多個(gè)查詢或更新,它是線程安全的
打開數(shù)據(jù)庫
- 通過指定SQLite數(shù)據(jù)庫文件路徑來創(chuàng)建FMDatabase對象
FMDatabase *db = [FMDatabase databaseWithPath:path]; if (![db open]) { NSLog(@"數(shù)據(jù)庫打開失?。?); }
- 文件路徑有三種情況
- 具體文件路徑:如果不存在會(huì)自動(dòng)創(chuàng)建
- 空字符串@"":會(huì)在臨時(shí)目錄創(chuàng)建一個(gè)空的數(shù)據(jù)庫,當(dāng)FMDatabase連接關(guān)閉時(shí),數(shù)據(jù)庫文件也被刪除
- nil:會(huì)創(chuàng)建一個(gè)內(nèi)存中臨時(shí)數(shù)據(jù)庫,當(dāng)FMDatabase連接關(guān)閉時(shí),數(shù)據(jù)庫會(huì)被銷毀
執(zhí)行更新
- 在FMDB中,除查詢以外的所有操作,都稱為“更新”
- create、drop、insert、update、delete等
- 使用executeUpdate:方法執(zhí)行更新
- (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"]
執(zhí)行查詢
- 查詢方法
- (FMResultSet *)executeQuery:(NSString*)sql, ... - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments // 查詢數(shù)據(jù) FMResultSet *rs = [db executeQuery:@"SELECT * FROM t_student"]; // 遍歷結(jié)果集 while ([rs next]) { NSString *name = [rs stringForColumn:@"name"]; int age = [rs intForColumn:@"age"]; double score = [rs doubleForColumn:@"score"]; }
FMDatabaseQueue
- FMDatabase這個(gè)類是線程不安全的,如果在多個(gè)線程中同時(shí)使用一個(gè)FMDatabase實(shí)例,會(huì)造成數(shù)據(jù)混亂等問題
-
為了保證線程安全,F(xiàn)MDB提供方便快捷的FMDatabaseQueue類
// FMDatabaseQueue的創(chuàng)建 FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path]; -
簡單使用
[queue inDatabase:^(FMDatabase *db) { [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Jack"]; [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Rose"]; [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Jim"]; FMResultSet *rs = [db executeQuery:@"select * from t_student"]; while ([rs next]) { // … } }]; -
使用事務(wù)
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) { [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Jack"]; [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Rose"]; [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Jim"]; FMResultSet *rs = [db executeQuery:@"select * from t_student"]; while ([rs next]) { // … } }]; -
事務(wù)回滾
rollback = YES;