FMDatabase 簡介
FMDB 是 iOS 上常用的 SQLite 封裝庫。使用步驟如下:
1. 下載 FMDB,導入其中的 src 檔案(可刪除 fmdb.m);
2. 引入 framework:libsqlite3.dylib;
3. 引入頭檔:#import "FMDatabase.h"。
資料庫檔案為了同時相容 iPhone 4 與 iPhone 5,需放在 Documents 或 Library 目錄中。做法是先判斷該目錄下的資料庫檔(一般為 .sqlite 後綴)是否存在,若不存在,則從工程(bundle)中把資料庫檔複製到 Documents 或 Library。
以下是一個實際專案中的資料庫操作程式碼,示範增刪查改與資料讀取:
// 數據庫操作,1代表增減,2代表刪除,3代表查詢,4代表修改
- (void)operateDB:(NSInteger)num andRow:(NSInteger)row status:(NSInteger)status {
self.deleteOld = YES;
self.dbFile = @"shopCar_db.sqlite";
NSFileManager *manager = [NSFileManager defaultManager];
NSString *dbPath = [Utilities documentsPath:self.dbFile];
// 沒存在則拷貝到 document
if (![manager fileExistsAtPath:dbPath]) {
NSString *bundlePath = [Utilities bundlePath:self.dbFile];
if ([manager copyItemAtPath:bundlePath toPath:dbPath error:nil]) {
NSLog(@"copy ok...");
} else {
NSLog(@"copy error...");
}
} else {
if (self.deleteOld) {
NSLog(@"delete old and create new..");
NSString *bundlePath = [Utilities bundlePath:self.dbFile];
[manager removeItemAtPath:dbPath error:nil];
[manager copyItemAtPath:bundlePath toPath:dbPath error:nil];
}
}
FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
if ([db open]) {
if (status == 1) { NSLog(@"增減......."); }
if (status == 2) {
NSString *sql = [NSString stringWithFormat:@"delete from shopCar_tb where id = %i", row];
[db executeUpdate:sql];
}
if (status == 3) { NSLog(@"查詢........"); }
if (status == 4) {
NSString *sql = [NSString stringWithFormat:@"UPDATE shopCar_tb SET num = '%d' WHERE id = %d", num, row];
[db executeUpdate:sql];
}
NSString *sql = @"select * from shopCar_tb";
FMResultSet *result = [db executeQuery:sql];
_mutableArrayData = [[NSMutableArray alloc] init];
[_mutableArrayData removeAllObjects];
[_mutableDictionayData removeAllObjects];
while ([result next]) {
_mutableDictionayData = [[NSMutableDictionary alloc] init];
[_mutableDictionayData setObject:[result stringForColumn:@"id"] forKey:@"id"];
[_mutableDictionayData setObject:[result stringForColumn:@"name"] forKey:@"name"];
[_mutableDictionayData setObject:[result stringForColumn:@"gid"] forKey:@"gid"];
[_mutableDictionayData setObject:[result stringForColumn:@"num"] forKey:@"num"];
[_mutableDictionayData setObject:[result stringForColumn:@"price"] forKey:@"price"];
[_mutableDictionayData setObject:[result stringForColumn:@"path"] forKey:@"path"];
[_mutableArrayData addObject:_mutableDictionayData];
}
}
[db close];
}透過 FMDatabase 的 open、executeUpdate、executeQuery 等方法,就能輕鬆完成資料庫的新增、刪除、修改與查詢操作。