您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iPhone SQLite3 資料庫實作教學:新增、刪除、修改與查詢

編輯:iOS 開發綜合

在 iPhone 開發中,SQLite 是常見的輕量級關聯式資料庫方案。若要在專案裡直接使用 sqlite3 API,第一步是把 libsqlite3.dylib 加入專案,並引入 sqlite3.h。

一、建立資料模型與資料庫包裝類

實務上通常會建立一個專門的資料庫類別,負責開啟資料庫、建立資料表,以及提供新增、刪除、修改、查詢等方法。以下以記事本為例。

#import <Foundation/Foundation.h>
#import "sqlite3.h"

@interface NoteSqlite : NSObject {
    sqlite3 *database;
    sqlite3_stmt *statement;
    char *errorMsg;
}
- (BOOL)open;
- (BOOL)create;
- (BOOL)insert:(NotePad *)aNote;
- (BOOL)deleteALLNote;
- (BOOL)deleteaNote:(NotePad *)aNote;
- (BOOL)update:(NotePad *)aNote;
- (NoteDb *)selecteAll;
- (NoteDb *)selectNotes:(NotePad *)aNote;
@end

二、開啟或建立資料庫

iOS App 只能存取自己的沙盒目錄。常見做法是把資料庫放在 Documents 目錄,先用 NSFileManager 判斷檔案是否存在;若不存在,就建立新檔並建立資料表。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"noteList.db"];

if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
    // 資料庫開啟成功
}

三、建立資料表

建立資料表可使用 sqlite3_exec。若資料表已存在,建議加上 IF NOT EXISTS,避免重複建立造成錯誤。

const char *createSql = "create table if not exists note (id integer primary key autoincrement, theme text, information text, ndate text, priority integer)";
sqlite3_exec(database, createSql, NULL, NULL, &errorMsg);

四、新增、刪除、修改與查詢

新增資料

新增資料時,可先以 NSString 組出 SQL,再轉成 UTF-8 字串交給 sqlite3 執行。

NSString *sql = [NSString stringWithFormat:@"insert into note (theme, information, ndate, priority) values ('%@', '%@', '%@', %d)", aNote.theme, aNote.information, aNote.ndate, aNote.priority];
sqlite3_exec(database, [sql UTF8String], NULL, NULL, &errorMsg);

刪除資料

刪除單筆資料時,通常以主鍵 id 作為條件;若要清空所有資料,可使用恆真條件,但正式專案建議改用 DELETE FROM note,語意更清楚。

NSString *deleteSql = [NSString stringWithFormat:@"delete from note where id=%d", aNote.noteId];
sqlite3_exec(database, [deleteSql UTF8String], NULL, NULL, &errorMsg);

修改資料

NSString *updateSql = [NSString stringWithFormat:@"update note set theme='%@', information='%@', ndate='%@', priority=%d where id=%d", aNote.theme, aNote.information, aNote.ndate, aNote.priority, aNote.noteId];
sqlite3_exec(database, [updateSql UTF8String], NULL, NULL, &errorMsg);

查詢資料

查詢時會使用 sqlite3_prepare_v2 與 sqlite3_step。每一列結果都可透過 sqlite3_column_int、sqlite3_column_text 取出,再封裝成模型物件。

const char *selectSql = "select * from note";
if (sqlite3_prepare_v2(database, selectSql, -1, &statement, nil) == SQLITE_OK) {
    while (sqlite3_step(statement) == SQLITE_ROW) {
        int noteId = sqlite3_column_int(statement, 0);
        NSString *theme = [NSString stringWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];
        // 繼續取出其他欄位並建立 NotePad 物件
    }
}

五、實作時的注意事項

使用 sqlite3 時,要特別注意錯誤訊息與資源釋放。若使用 sqlite3_exec 發生錯誤,可透過 errorMsg 取得原因,並以 sqlite3_free 釋放。查詢使用的 statement 在不再需要時,也應適度 reset 或 finalize,避免資源累積。

整體流程可以整理為:加入 sqlite3 函式庫、建立資料庫包裝類、開啟或建立資料庫、建立資料表、實作 CRUD,最後在需要時關閉資料庫。掌握這個順序,就能在 iPhone App 中穩定使用 SQLite。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved