天天看點

sqlite第三方類庫:FMDB使用---1

轉自:http://www.cnblogs.com/wuhenke/archive/2012/02/07/2341656.html 本文轉自一位台灣ios開發者的blog,由于blog位址被牆掉,轉發過來,供大家參考

原文位址: 首先到這裡下載下傳FMDB的source code,接著在解開的檔案裡,把src資料夾下除了fmdb.m的檔案加入到自己的iOS專案,最後在專案中加入libsqlite3.dylib這個函式庫就可以了。啥?有人問為什麼不用加入fmdb.m?簡單講,這個檔案是fmdb的使用說明。裡面的註解清楚,範例又簡單,如果有興趣,直接看fmdb.m,大概就會用fmdb了。 以下介紹幾個常用的指令,分享給大家: -打開/關閉資料庫 使用資料庫的第一件事,就是建立一個資料庫。要注意的是,在iOS環境下,隻有document directory 是可以進行讀寫的。在寫程式時用的那個Resource資料夾底下的東西都是read-only。是以,建立的資料庫要放在document 資料夾下。方法如下: 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentDirectory = [paths objectAtIndex:0];

NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"MyDatabase.db"];

FMDatabase *db = [FMDatabase databaseWithPath:dbPath] ;

if (![db open]) {

   NSLog(@“Could not open db.”);

   return ;

}

建立table 

如果是建立的資料庫檔,一開始是沒有table的。建立table的方式很簡單:

1

[db executeUpdate:@

"CREATE TABLE PersonList (Name text, Age integer, Sex integer, Phone text, Address text, Photo blob)"

];

這是FMDB裡很常用的指令,[FMDatabase_object executeUpdate:]後面用NSString塞入SQLite文法,就解決了。因為這篇主要是在講FMDB,是以SQLite的文法就不多說了,上述程式碼建立了一個名為PersonList的table,裡面有姓名、年齡、性别、電話、位址和照片。(嗯….很範例的一個table)

-插入資料 插入資料跟前面一樣,用executeUpdate後面加文法就可以了。 比較不同的是,因為插入的資料會跟Objective-C的變數有關,是以在string裡使用?号來代表這些變數。

1

[db executeUpdate:@

"INSERT INTO PersonList (Name, Age, Sex, Phone, Address, Photo) VALUES (?,?,?,?,?,?)"

,

3

@

"Jone"

, [NSNumber numberWithInt:20], [NSNumber numberWithInt:0], @“091234567”, @“Taiwan, R.O.C”, [NSData dataWithContentsOfFile: filepath]];

其中,在SQLite中的text對應到的是NSString,integer對應NSNumber,blob則是NSData。該做的轉換FMDB都做好了,隻要了解SQLite文法,應該沒有什麼問題才是。 -更新資料 太簡單了,不想講,請看範例:

1

[db executeUpdate:@

"UPDATE PersonList SET Age = ? WHERE Name = ?"

,[NSNumber numberWithInt:30],@“John”];

-取得資料 取得特定的資料,則需使用FMResultSet物件接收傳回的内容:

01

FMResultSet *rs = [db executeQuery:@

"SELECT Name, Age, FROM PersonList"

];

03

while

([rs next]) {

05

NSString *name = [rs stringForColumn:@

"Name"

];

07

int age = [rs intForColumn:@

"Age"

];

09

}

11

[rs close];

用[rs next]可以輪詢query回來的資料,每一次的next可以得到一個row裡對應的數值,并用[rs stringForColumn:]或[rs intForColumn:]等方法把值轉成Object-C的型态。取用完資料後則用[rs close]把結果關閉。 -快速取得資料 在有些時候,隻會query某一個row裡特定的一個數值(比方隻是要找John的年齡),FMDB提供了幾個比較簡便的方法。這些方法定義在FMDatabaseAdditions.h,如果要使用,記得先import進來。

1

//找位址

3

NSString *address = [db stringForQuery:@

"SELECT Address FROM PersonList WHERE Name = ?"

,@"John”];

5

//找年齡

7

int age = [db intForQuery:@

"SELECT Age FROM PersonList WHERE Name = ?"

,@"John”];