iOS 使用FMDB進行資料庫操作(一)

2021-07-02 17:06:00 字數 2362 閱讀 9647

1、首先要先導入第三方類庫fmdatabase。

2、獲得存放資料庫檔案的沙盒位址。

view row code

1+(nsstring

*)databasefilepath 2

3、建立資料庫的操作

view row code

1+(void)creatdatabase 2

4、建立表

view row code

1+(void)creattable 2 

7//判斷資料庫是否已經開啟,如果沒有開啟,提示失敗 

8if (!

[db open

])  

1213

//為資料庫設定快取,提高查詢效率 14[

dbsetshouldcachestatements:

yes]; 

1516

//判斷資料庫中是否已經存在這個表,如果不存在則建立該錶

17if(!

[dbtableexists:

@"people"

]) 18 24

25}5、增加表資料

view row code

1+(void)insertpeople:(people

*)apeople 2 

67if (!

[db open

])  

1112

[dbsetshouldcachestatements:

yes]; 

1314

if(!

[dbtableexists:

@"people"

]) 15 18

//以上操作與建立表是做的判斷邏輯相同

19//現在表中查詢有沒有相同的元素,如果有,做修改操作 

20fmresultset

*rs =

[dbexecutequery:

@"select * from people where people_id = ?",[

nsstringstringwithformat:

@"%d",apeople.peopleid]

]; 21

if([rs next

]) 22 26

//向資料庫中插入一條資料 

27else 

3031}

6、刪除資料

view row code

1+(void)deletepeoplebyid:(int)id2 

67if (!

[db open

])  

1112

[dbsetshouldcachestatements:

yes]; 

1314

//判斷表中是否有指定的資料, 如果沒有則無刪除的必要,直接return

15if(!

[dbtableexists:

@"people"

]) 16 19

//刪除操作 

20[db executeupdate:

@"delete from people where people_id = ?", [

nsstringstringwithformat:

@"%d",id

]]; 

2122

[db close

]; 23}

7、修改操作與增加操作的步驟一致

8、查詢

view row code

1+(nsarray

*)getallpeople 2 

78if (!

[db open

])  

1213

[dbsetshouldcachestatements:

yes]; 

1415

if(!

[dbtableexists:

@"people"

]) 16 19

20//定義乙個可變陣列,用來存放查詢的結果,返回給呼叫者 

21nsmutablearray

*peoplearray =[[

nsmutablearrayalloc

]initwitharray:

0]; 

22//定義乙個結果集,存放查詢的資料

23fmresultset

*rs =

[dbexecutequery:

@"select * from people"

]; 24

//判斷結果集中是否有資料,如果有則取出資料

25while ([rs next

])  

34return

[peoplearray autorelease

]; 35}

使用FMDB進行資料庫操作

fmdb fmdb有三個主要的類 1.fmdatabase 表示乙個單獨的sqlite資料庫。用來執行sqlite的命令。2.fmresultset 表示fmdatabase執行查詢後結果集 3.fmdatabasequeue 如果你想在多執行緒中執行多個查詢或更新,你應該使用該類。這是執行緒安全的...

OC 資料庫儲存,使用FMDB進行資料庫操作

第一種 乙個資料庫中,同時儲存多張資料表 此處舉例為兩張表 h檔案 import class goodsdetailsvo extern nsstring datastoretype int level extern nsstring tablename inte ce databasecenter...

iOS 資料庫 FMDB使用

好久沒有寫oc 了,幹了一年的cocos2d x,終於又回歸ios了,這段時間翻看了以前寫的,試圖控制項基本總結完畢,還有一些不常用的以後再補充。後面有時間就寫一些其他的。今天就先寫一下資料庫和乙個三方fmdb。其實ios的資料儲存形式有很多,比如 檔案形式,nsuserdefault,資料庫等。檔...