本文轉自一位臺灣ios開發者的blog,由於blog地址被牆掉,轉發過來,供大家參考
原文地址:
原文地址:
2 |
NSString
*documentDirectory = [paths objectAtIndex:0]; |
4 |
FMDatabase
*db = [FMDatabase databaseWithPath:dbPath] ; |
6 |
NSLog(@“Could
not open db.”); |
8 |
} |
建立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”]; |