- The only limit is your imagination. 唯一的局限是你的想象力降传。
我是新手,一個不折不扣的新手声旺,永遠在追趕別人段只,此次出寫,就是綜合下班上的中午分享赞枕,和大神們的博客炕婶,有問題希望大家說出來,一起探討柠掂,致謝涯贞!
FMDB同時兼容ARC和非ARC工程,會自動根據(jù)工程配置來調整相關的內(nèi)存管理代碼肩狂。
FMDB有三個主要的類
1.FMDatabase – 表示一個單獨的SQLite數(shù)據(jù)庫傻谁。 用來執(zhí)行SQLite的命令。
2.FMResultSet – 表示FMDatabase執(zhí)行查詢后結果集审磁,這個和Android的Cursor類似态蒂。
3.FMDatabaseQueue – 如果你想在多線程中執(zhí)行多個查詢或更新,你應該使用該類钾恢。這是線程安全的。
數(shù)據(jù)庫創(chuàng)建
創(chuàng)建FMDatabase對象時參數(shù)為SQLite數(shù)據(jù)庫文件路徑泉懦。該路徑可以是以下三種之一:
1..文件路徑。該文件路徑無需真實存崩哩,如果不存在會自動創(chuàng)建。
2..空字符串(@”")酣栈。表示會在臨時目錄創(chuàng)建一個空的數(shù)據(jù)庫汹押,當FMDatabase 鏈接關閉時,文件也被刪除跋涣。
3.NULL. 將創(chuàng)建一個內(nèi)在數(shù)據(jù)庫鸟悴。同樣的,當FMDatabase連接關閉時沛贪,數(shù)據(jù)會被銷毀震贵。
直接上手例子,邊走邊說:
這次分享前期準備了一個model
Person.h 文件中
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h> @interface Person : NSObject @property(nonatomic, copy)NSString *name; @property(nonatomic, copy)NSString * gender; @property(nonatomic)NSInteger age,ID;//基本數(shù)據(jù)類型可以省略內(nèi)存修飾符assign,因為默認使用的就是assign @property(nonatomic,strong)UIImage *photo; //自定義初始化方法 -(id)initWithName : (NSString *)name gender : (NSString *)gender age : (NSInteger)age photo : (UIImage *)photo; @end
Person.m文件
#import "Person.h" @implementation Person//自定義初始化方法 -(id)initWithName : (NSString *)name gender : (NSString *)gender age : (NSInteger)age photo : (UIImage *)photo{ if (self = [super init]) { self.name = name; self.gender = gender; self.age = age; self.photo = photo; } return self; } @end
打開數(shù)據(jù)庫
在和數(shù)據(jù)庫交互 之前,數(shù)據(jù)庫必須是打開的寇甸。如果資源或權限不足無法打開或創(chuàng)建數(shù)據(jù)庫,都會導致打開失敗吟秩。
`-(void)viewDidLoad {
[super viewDidLoad];
// 獲取Documents文件夾路徑
NSString *urlString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
// 在Documents文件夾里創(chuàng)建數(shù)據(jù)庫文件 db.sqlite
NSString *dbPath = [urlString stringByAppendingPathComponent:@"db.sqlite"];
// 創(chuàng)建數(shù)據(jù)庫對象
// 參數(shù):數(shù)據(jù)庫的路徑
// 執(zhí)行結束后并沒有幫我們生成數(shù)據(jù)庫文件,只是幫我們創(chuàng)建了數(shù)據(jù)庫對象
FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
NSLog(@"%@",NSHomeDirectory());
// 代開數(shù)據(jù)庫
// open操作才幫我們真正的創(chuàng)建數(shù)據(jù)庫文件,且如果已經(jīng)打開,直接返回YES,此時可以直接使用涵防,如果打開失敗會打印報錯信息
BOOL isOpen = [db open];
if (isOpen) {
NSLog(@"打開成功");
//創(chuàng)建表格
//executeUpdate 除了查詢之外沪铭,其他數(shù)據(jù)創(chuàng)建表格偏瓤,插入數(shù)據(jù)椰憋、刪除數(shù)據(jù)都是用這個方法
// blob 二進制流 相當于oc的NSData
BOOL isCreat = [db executeUpdate:@"create table if not exists Person(id integer primary key autoincrement,name text,gender text,age integer,photo blob)"];
NSLog(@"%@",isCreat ? @"建表成功":@"建表失敗");
}else{
NSLog(@"打開失敗");
}
//給屬性賦值
self.db = db;
NSLog(@"%@",NSHomeDirectory());
// 可以根據(jù)打印的地址熏矿,自行查看
}`
執(zhí)行更新
一切不是SELECT命令的命令都視為更新离钝。這包括 CREATE, UPDATE, INSERT,ALTER,COMMIT, BEGIN, DETACH, DELETE, DROP, END, EXPLAIN, VACUUM, and REPLACE (等)。
簡單來說慧域,只要不是以SELECT開頭的命令都是UPDATE命令浪读。
執(zhí)行更新返回一個BOOL值。YES表示執(zhí)行成功互订,否則表示有那些錯誤 痘拆。你可以調用 -lastErrorMessage 和 -lastErrorCode方法來得到更多信息。
// 插入
- (IBAction)insertButtonAction:(id)sender { Person *p = [[Person alloc]initWithName:@"美美" gender:@"女" age:20 photo:[UIImage imageNamed:@"3.gif"]]; //將圖片轉化成NSData對象 NSData *data = UIImagePNGRepresentation(p.photo); //@(p.age)參數(shù)必須是對象類型的才能使用 //插入操作 BOOL isInsert = [self.db executeUpdate:@"insert into Person(name,gender,age,photo)values(?,?,?,?)",p.name,p.gender,@(p.age),data]; NSLog(@"%@",isInsert ? @"插入成功":@"插入失敗"); if (isInsert == YES) { NSLog(@"插入成功"); }else{ NSLog(@"插入失敗"); } }
// 刪除
- (IBAction)deleteButtonAction:(id)sender { //根據(jù)條件刪除 BOOL result = [self.db executeUpdate:@"delete from Person where id = ?",@1]; if (result == YES) { NSLog(@"刪除成功"); }else{ NSLog(@"刪除失敗"); } //刪除全部表格內(nèi)容 // id 不會清空 // BOOL isResult1 = [self.db executeUpdate:@"delete from Person"]; // 刪除表格 // id 清空 // BOOL isResult2 = [self.db executeUpdate:@"drop table Person"]; }
// 更新
`- (IBAction)updataButtonActton:(id)sender {
BOOL isUpdate = [self.db executeUpdate:@"update Person set gender = ? where id = ?",@"男",@4];
if (isUpdate == YES) {
NSLog(@"更新成功");
}else{
NSLog(@"更新入失敗");
}
}`
執(zhí)行查詢
SELECT命令就是查詢,執(zhí)行查詢的方法是以 -excuteQuery開頭的温峭。
執(zhí)行查詢時字支,如果成功返回FMResultSet對象, 錯誤返回nil. 與執(zhí)行更新相當祥款,支持使用 NSError**參數(shù)刃跛。同時,你也可以使用 -lastErrorCode和-lastErrorMessage獲知錯誤信息桨昙。
// 查詢
- (IBAction)selectButtonActton:(id)sender { // 查詢?nèi)?FMResultSet *set = [self.db executeQuery:@"select * from Person"]; // 按條件查詢 // FMResultSet *set = [self.db executeQuery:@"select *from Person where name = ?",@"美美"]; self.dataArray = [NSMutableArray arrayWithCapacity:0]; // 循環(huán)取出表中的數(shù)據(jù) // [set next] 判斷寫一行是否有數(shù)據(jù) // [set next]可以輪詢query回來的資料,每一次的next可以得到一個row里對應的數(shù)值翘盖,并用[rs stringForColumn:]或[rs intForColumn:]等方法把值轉成Object-C的型態(tài)凹蜂。 // if [FMResultSet next] 查詢某一條信息 while ([set next]) { //取出每一個字段對應的數(shù)據(jù) NSInteger ID = [set intForColumn:@"id"]; //取出id字段下的數(shù)據(jù) NSString *name = [set stringForColumn:@"name"];//取出name字段下的數(shù)據(jù) NSString *gender = [set stringForColumn:@"gender"];//取出gender字段下的數(shù)據(jù) NSInteger age = [set intForColumn:@"age"];//取出age字段下的數(shù)據(jù) NSData *data = [set dataForColumn:@"photo"];//取出photo字段下的數(shù)據(jù) //創(chuàng)建model類 //將二進制流轉成圖片 UIImage *image = [UIImage imageWithData:data]; Person *p = [[Person alloc]initWithName:name gender:gender age:age photo: image]; p.ID = ID; // 保存你需要的信息 [self.dataArray addObject:p]; } }
FMResultSet 提供了很多方法來獲得所需的格式的值:
intForColumn:
longForColumn:
longLongIntForColumn:
boolForColumn:
doubleForColumn:
stringForColumn:
dataForColumn:
dataNoCopyForColumn:
UTF8StringForColumnIndex:
objectForColumn:
這些方法也都包括 {type}ForColumnIndex 的這樣子的方法玛痊,參數(shù)是查詢結果集的列的索引位置。
你無需調用 [FMResultSet close]來關閉結果集, 當新的結果集產(chǎn)生擂煞,或者其數(shù)據(jù)庫關閉時,會自動關閉蝗拿。
關閉數(shù)據(jù)庫
當使用完數(shù)據(jù)庫蒿涎,你應該 -close 來關閉數(shù)據(jù)庫連接來釋放SQLite使用的資源同仆。
[db close];
事務
FMDatabase是支持事務的。
數(shù)據(jù)凈化(數(shù)據(jù)格式化)
使用FMDB俗批,插入數(shù)據(jù)前岁忘,你不要花時間審查你的數(shù)據(jù)。你可以使用標準的SQLite數(shù)據(jù)綁定語法干像。
INSERT INTO myTable VALUES (?, ?, ?)
SQLite會識別 “?” 為一個輸入的點位符麻汰, 這樣的執(zhí)行會接受一個可變參數(shù)(或者表示為其他參數(shù),如NSArray, NSDictionary,或va_list等)五鲫,會正確為您轉義。
你也可以選擇使用命名參數(shù)語法浪耘。
INSERT INTO myTable VALUES (:id, :name, :value)
參數(shù)名必須以冒名開頭。SQLite本身支持其他字符痛倚,當Dictionary key的內(nèi)部實現(xiàn)是冒號開頭澜躺。注意你的NSDictionary key不要包含冒號。
NSDictionary *argsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"My Name", @"name", nil];
[db executeUpdate:@"INSERT INTO myTable (name) VALUES (:name)" withParameterDictionary:argsDict];
而且颠区,代碼不能這么寫(為什么通铲?想想吧颅夺。)
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @"this has \\" lots of ' bizarre \\" quotes '"];
你應該:
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @"this has " lots of ' bizarre " quotes '"];
提供給 -executeUpdate: 方法的參數(shù)都必須是對象蛹稍。就像以下的代碼就無法工作,且會產(chǎn)生崩潰拗慨。
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", 42];
正確有做法是把數(shù)字打包成 NSNumber對象
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:42]];
或者奉芦,你可以使用 -execute*WithFormat: ,這是NSString風格的參數(shù)
[db executeUpdateWithFormat:@"INSERT INTO myTable VALUES (%d)", 42];
-execute*WithFormat: 的方法的內(nèi)部實現(xiàn)會幫你封裝數(shù)據(jù)烦却, 以下這些修飾符都可以使用: %@, %c, %s, %d, %D,%i, %u, %U, %hi, %hu, %qi, %qu, %f, %g, %ld, %lu, %lld, and %llu. 除此之外的修飾符可能導致無法預知的結果先巴。 一些情況下,你需要在SQL語句中使用 % 字符摩渺,你應該使用 %%剂邮。
線程安全
如果我們的 app 需要多線程操作數(shù)據(jù)庫,那么就需要使用 FMDatabaseQueue 來保證線程安全了囚企。 切記不能在多個線程中共同一個 FMDatabase 對象并且在多個線程中同時使用,這個類本身不是線程安全的棵逊,這樣使用會造成數(shù)據(jù)混亂等問題银酗。
使用 FMDatabaseQueue 很簡單,首先用一個數(shù)據(jù)庫文件地址來初使化 FMDatabaseQueue蛙讥,然后就可以將一個閉包 (block) 傳入 inDatabase 方法中灭衷。 在閉包中操作數(shù)據(jù)庫,而不直接參與 FMDatabase 的管理翔曲。
// 創(chuàng)建,最好放在一個單例的類中
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; // 使用[queue inDatabase:^(FMDatabase *db) { [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; FMResultSet *rs = [db executeQuery:@"select * from foo"]; while ([rs next]) { // … } }]; // 如果要支持事務 [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; if (whoopsSomethingWrongHappened) { *rollback = YES; return; } // etc… [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; }];
本文后期的事務和多線程沒有什么想法就什么也沒有添加。
本文章大部分都是別人的掠械,我是為了做個筆記,也多個東西給大家參考下
轉自:
唐巧超級大神引用
FMDB官方使用文檔-GCD的使用-提高性能(翻譯)