1、開啟資料庫
先要獲取沙盒的資料庫檔名,並建立資料庫檔名,定資料庫:
@property (nonatomic, strong) fmdatabase *db;
// 0.獲得沙盒中的資料庫檔名
nsstring *filename = [[nssearchpathfordirectoriesindomains(nsdocumentdirectory,
// 1.建立資料庫例項物件
self.db = [fmdatabase databasewithpath:filename];
// 2.開啟資料庫
if ( [self.db open] ) else
} else
2、fmdb的核心類
fmdb有三個主要的類:
fmdatabase:乙個fmdatabase物件就代表乙個單獨的sqlite資料庫;用來執行sql語句
fmresultset:使用fmdatabase執行查詢後的結果集
fmdatabasequeue:用於在多執行緒中執行多個查詢或更新,它是執行緒安全的
3、執行更新
使用executeupdate:方法執行更新:
- (bool)executeupdate:(nsstring*)sql, ... // 新增資料庫更新語句,除了查詢,其他都用更新語句
- (bool)executeupdatewithformat:(nsstring*)format, ...
-(bool)executeupdate:(nsstring*)sql withargumentsinarray:(nsarray *)arguments
4、執行查詢
- (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])
5、fmdb事務的使用
// 開啟事務
[db begintransaction];
// [db executeupdate:@"begin transaction;"];
// 更新資料
[db executeupdate:@"update t_student set age = ? where name = ?;", @20, @"jack"];
[db executeupdate:@"update t_student set age = ? where name = ?;", @20, @"jack"];
// 提交事務
[db commit];
//[db executeupdate:@"commit transaction;"];
注意:其中有一條失敗了,就會出錯,發現情況不對,可以使用回滾事務:
if (發現情況不對)
SQL資料庫相關 FMDB框架的使用
sqlite是乙個開源的嵌入式關聯式資料庫,它在2000年由d.richard hipp發布,它的減少應用程式管理資料的開銷,sqlite可移植性好,很容易使用,很小,高效而且可靠。sqlite嵌入到使用它的應用程式中,它們共用相同的程序空間,而不是單獨的乙個程序。從外部看,它並不像乙個rdbms,...
資料庫操作 使用FMDB
ios中原生的sqlite api在使用上相當不友好,在使用時,非常不便。於是,就出現了一系列將sqlite api進行封裝的庫,例如fmdb plausibledatabase sqlitepersistentobjects等,fmdb 是一款簡潔 易用的封裝庫,這一篇文章簡單介紹下fmdb的使用...
資料庫操作 使用FMDB
ios中原生的sqlite api在使用上相當不友好,在使用時,非常不便。於是,就出現了一系列將sqlite api進行封裝的庫,例如fmdb plausibledatabase sqlitepersistentobjects等,fmdb 是一款簡潔 易用的封裝庫,這一篇文章簡單介紹下fmdb的使用...