FMDB的基本使用

2021-12-30 01:14:11 字數 2621 閱讀 1230

首先資料庫是系統資源,就像我們操作檔案一樣,所以併發操作時要注意安全。在ios上,只有乙個執行緒能夠開啟資料庫操作,其他執行緒要運算元據庫必須等資料庫關閉後才能開啟操作。

ios中原生的sqliteapi在進行資料儲存的時候,需要使用c語言中的函式,操作比較麻煩。於是,就出現了一系列將sqlite api進行封裝的庫,其中使用比較多的例如fmdb,fmdb是對libsqlite3框架的封裝,用起來的步驟與sqlite使用類似,並且它對於多執行緒的併發操作進行了處理,所以是執行緒安全的。fmdb_github

● fmdb優點:

使用起來更加物件導向,省去了很多麻煩、冗餘的c語言**

對比蘋果自帶的coredata框架,更加輕量級和靈活

提供多執行緒安全,有效地防止資料混亂,原來的sqlite不是執行緒安全的

● fmdb缺點:

因為是oc語言封裝的,失去了sqlite原來的跨平台性(相對於其他語言)

● fmdb框架中重要的框架類:

fmdatabase

fmdatabase物件就代表乙個單獨的sqlite資料庫,用來執行sql語句

fmresultset

使用fmdatabase執行查詢後的結果集

fmdatabasequeue

用於在多執行緒中執行多個查詢或更新,執行緒安全。

● fmdatabase建立資料庫

在建立資料庫之前,我們應該了解的

① 如果該路徑下已經存在該資料庫,直接獲取該資料庫;

② 如果不存在就建立乙個新的資料庫;

③ 如果傳@"",會在臨時目錄建立乙個空的資料庫,當資料庫關閉時,資料庫檔案也被刪除;

④ 如果傳nil,會在記憶體中臨時建立乙個空的資料庫,當資料庫關閉時,資料庫檔案也被刪除;

**示例

1.獲得資料庫檔案的路徑

nsstring*doc =[nssearchpathfordirectoriesindomains(nsdocumentdirectory,nsuserdomainmask,yes) lastobject];

nsstring*filename = [doc stringbyappendingpathcomponent:@「student.sqlite」];2.獲得資料庫

fmdatabase *db = [fmdatabase databasewithpath:filename];

3.使用如下語句,如果開啟失敗,可能是許可權不足或者資源不足。通常開啟完操作操作後,需要呼叫 close 方法來關閉資料庫。在和資料庫互動 之前,資料庫必須是開啟的。如果資源或許可權不足無法開啟或建立資料庫,都會導致開啟失敗。

if([db open])

}● 使用fmdatabase類執行資料庫命令sql

一切不是select命令的命令都視為更新。這包括 creat,update,insert,alter,begin,commit,detach,delete,drop,end,explain,vacuum,replace等。簡單來說,只要不是以select開頭的命令都是更新命令。

執行更新返回乙個bool值。yes表示 執行成功,否則表示有錯誤。你可以呼叫 -lasterrormessage 和 -lasterrorcode方法來得到更多資訊。

使用fmdatabase類執行資料庫插入命令sql insert into

int age = 42;

1.executeupdate:

不確定的引數用?來佔位(後面引數必須是oc物件,;代表語句結束) [self.db executeupdate:@「insertintot_student (name, age)values(?,?);」,name,@(age)];2.executeupdatewithforamat:

不確定的引數用%@,%d等來佔位 (引數為原始資料型別,執行語句不區分大小寫) [self.db executeupdatewithforamat:@「insertintot_student (name,age)values(%@,%i);」,name,age];3.引數是陣列的使用方式

[self.db executeupdate:@「insertintot_student(name,age)values(?,?);」withargumentsinarray:@[name,@(age )]];這裡只講insert into,其他的操作類似,是對sql語句的考察。

●fmresultset獲取不同資料格式的方法

○ intforcolumn:

○ longforcolumn:

○ longlongintforcolumn:

○ boolforcolumn:

○ doubleforcolumn:

○ stringforcolumn:

○ dataforcolumn:

○ datanocopyforcolumn:

○ utf8stringforcolumnindex:

○ objectforcolumn:

●使用fmdatabasequeue類實現多執行緒操作

fmdatabasequeue解決fmdatabase同時運算元據庫這個問題的思路是:建立乙個佇列,然後將放入佇列的block順序執行,這樣避免了多執行緒同時訪問資料庫。

可能我還不會用簡書,我發現**沒辦法很清晰的展現( ̄. ̄),所以有些**我就不在這裡展示了,以後我會上傳到github乙份demo,到時候把位址發到這裡。

FMDB基本使用

import 建立乙個類 import ns assume nonnull begin inte ce dbdcachetool nsobject void set end import dbdcachetool.h import implementation dbdcachetool void s...

FMDB 基本使用

0.拼接資料庫存放的沙盒路徑 nsstring path nssearchpathfordirectoriesindomains nsdocumentdirectory,nsuserdomainmask,yes lastobject 1.通過路徑建立資料庫 fmdatabase db fmdatab...

使用FMDB 基本操作

建立,插入,更新和刪除 使用executeupdate方法,而查詢則用executequery 1.例項化fmdatabase paths ios下document路徑,document為ios中可讀寫的資料夾 nsarray paths nssearchpathfordirectoriesindo...