FMDatabase.m(若只使用核心查詢功能,這個檔案用不到)。libsqlite3.dylib 這個 framework。#import "FMDatabase.h"。資料庫檔案要同時相容 iPhone 4 與 iPhone 5,必須放在 Documents 或 Library 目錄中。做法是:先判斷 Documents/Library 下是否已有該資料庫檔(一般為 .sqlite 副檔名),若不存在,就從專案 bundle 中把它複製過去。這一步不能省略,因為 bundle 是唯讀的,直接對它寫入會失敗。
以下是我專案中的一段操作程式碼,紀錄下來以免忘記。這裡用一個 status 參數把增、刪、查、改四種操作收在同一個方法裡。
// status: 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];
// 不存在則從 bundle 複製一份過去
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) {
// 每次都重建,適合 demo;正式環境應該移除這段
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];
NSLog(@"begin to db...");
if ([db open]) {
if (status == 1) {
NSLog(@"新增......");
}
if (status == 2) {
NSString *sql = [NSString stringWithFormat:
@"delete from shopCar_tb where id = %d", (int)row];
[db executeUpdate:sql];
}
if (status == 3) {
NSLog(@"查詢........");
}
if (status == 4) {
NSString *sql = [NSString stringWithFormat:
@"UPDATE shopCar_tb SET num = '%d' WHERE id = %d", (int)num, (int)row];
[db executeUpdate:sql];
}
// 無論哪種操作,最後都重新撈一次全表
FMResultSet *result = [db executeQuery:@"select * from shopCar_tb"];
_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];
}
NSLog(@"end db...");
}
第一,deleteOld 那段邏輯每次執行都會把資料庫砍掉重建,這是除錯時的臨時手段,正式環境務必移除,否則使用者每次開 App 資料就歸零。
第二,用 stringWithFormat: 拼 SQL 有資安風險。若拼進來的值含有單引號就會造成語法錯誤,若值來自使用者輸入更是 SQL injection 的入口。正確做法是用 executeUpdate:withArgumentsInArray: 搭配佔位符:
[db executeUpdate:@"UPDATE shopCar_tb SET num = ? WHERE id = ?",
@(num), @(row)];
第三,用一個 status 數字分支處理四種操作,讓方法變長且難以擴充。比較好的做法是把增刪查改拆成四個獨立方法,各自單一職責,呼叫端意圖也更明確。
第四,FMDB 提供 FMDatabaseQueue 專門處理執行緒問題。SQLite 連線不支援多執行緒同時操作,若你的查詢可能在背景執行,用 queue 可以省下自己加鎖的功夫。
最後,FMResultSet 取值時優先用型別明確的方法(intForColumn:、doubleForColumn:),而不是一律 stringForColumn: 再自行轉型,能少掉一堆不必要的型別轉換與錯誤可能。