ios資料庫操作SQLite

來源:互聯網
上載者:User

標籤:

iPhone中支援通過sqlite3來訪問iPhone本地的資料庫。具體使用方法如下1:添加開發包libsqlite3.0.dylib首先是設定專案檔,在項目中添加iPhone版的sqlite3的資料庫的開發包,在項目下的Frameworks點擊右鍵,然後選擇libsqlite3.0.dylib檔案。libsqlite3.0.dylib檔案地址: /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk/usr/lib/libsqlite3.0.dylib2,代碼中的操作:那麼接下來是代碼了。1 首先擷取iPhone上sqlite3的資料庫檔案的地址NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];NSString *path = [documentsDirectory stringByAppendingPathComponent:@"database_name"];2 開啟iPhone上的sqlite3的資料庫檔案sqlite3 *database;sqlite3_open([path UTF8String], &database);3 準備sql文---sql語句sqlite3_stmt *stmt;const char *sql = "SELECT * FROM table_name WHERE pk=? and name=?";sqlite3_prepare_v2(database, sql, -1, &stmt, NULL);4 邦定參數// 邦定第一個int參數sqlite3_bind_int(stmt, 1, 1);// 邦定第二個字串參數sqlite3_bind_text(stmt, 2, [title UTF8String], -1, SQLITE_TRANSIENT);5 執行sql文sqlite3_step(stmt);6 釋放sql文資源sqlite3_finalize(stmt);7 關閉iPhone上的sqlite3的資料庫sqlite3_close(database);http://hi.baidu.com/clickto/blog/item/0c6904f787c34125720eec87.html以下示範一下使用sqlite的步驟,先建立一個資料庫,然後查詢其中的內容。2個重要結構體和5個主要函數:sqlite3               *pdb, 資料庫控制代碼,跟檔案控制代碼FILE很類似sqlite3_stmt      *stmt, 這個相當於ODBC的Command對象,用於儲存編譯好的SQL語句sqlite3_open(),   開啟資料庫sqlite3_exec(),   執行非查詢的sql語句sqlite3_prepare(), 準備sql語句,執行select語句或者要使用parameter bind時,用這個函數(封裝了sqlite3_exec).Sqlite3_step(), 在調用sqlite3_prepare後,使用這個函數在記錄集中移動。Sqlite3_close(), 關閉資料庫檔案還有一系列的函數,用於從屬記錄集欄位中擷取資料,如sqlite3_column_text(), 取text類型的資料。sqlite3_column_blob(),取blob類型的資料sqlite3_column_int(), 取int類型的資料PreparedStatement方式處理SQL請求的過程特點:可以綁定參數,產生過程。執行的時候像是ADO一樣,每次返回一行結果。1. 首先建立statement對象:int sqlite3_prepare(  sqlite3 *db,            /* Database handle */  const char *zSql,       /* SQL statement, UTF-8 encoded */  int nBytes,             /* Length of zSql in bytes. */  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */  const char **pzTail     /* OUT: Pointer to unused portion of zSql */);2. 綁定過程中的參數(如果有沒有確定的參數)   int sqlite3_bind_xxxx(sqlite3_stmt*, int, ...);第二個int型別參數-表示參數的在SQL中的序號(從1開始)。第三個參數為要綁定參數的值。  對於blob和text數值的額外參數:第四參數是字串(Unicode 8or16)的長度,不包括結束‘\0‘。第五個參數,類型為void(*)(void*),表示SQLite處理結束後用於清理參數字串的函數。沒有進行綁定的未知參數將被認為是NULL。3. 執行過程  int sqlite3_step(sqlite3_stmt*);可能的傳回值: *SQLITE_BUSY:   資料庫被鎖定,需要等待再次嘗試直到成功。 *SQLITE_DONE:   成功執行過程(需要再次執行一遍以恢複資料庫狀態) *SQLITE_ROW:    返回一行結果(使用sqlite3_column_xxx(sqlite3_stmt*,, int iCol)得到每一列的結果。         再次調用將返回下一行的結果。 *SQLITE_ERROR:  運行錯誤,過程無法再次調用(錯誤內容參考sqlite3_errmsg函數傳回值) *SQLITE_MISUSE: 錯誤的使用了本函數(一般是過程沒有正確的初始化)4. 結束的時候清理statement對象  int sqlite3_finalize(sqlite3_stmt *pStmt);應該在關閉資料庫之前清理過程中佔用的資源。5. 重設過程的執行   int sqlite3_reset(sqlite3_stmt *pStmt);過程將回到沒有執行之前的狀態,綁定的參數不會變化。其他工具函數1. 得到結果總共的行數  int sqlite3_column_count(sqlite3_stmt *pStmt);如果過程沒有傳回值,如update,將返回02. 得到當前行中包含的資料個數  int sqlite3_data_count(sqlite3_stmt *pStmt);如果sqlite3_step返回SQLITE_ROW,可以得到列數,否則為零。3. 得到資料行中某個列的資料  sqlite3_column_xxx(sqlite3_stmt*, int iCol);在sqlite3_step返回SQLITE_ROW後,使用它得到第iCol列的資料。其中的xxx代表:blob:指向儲存資料記憶體的指標bytes, bytes16: 得到該blob類型資料的大小,或者text轉換為UTF8/UTF16的字串長度。double, int, int64: 數值text,text16:字串指標type:該列的資料類型(SQLITE_INTEGER,SQLITE_FLOAT,SQLITE_TEXT,SQLITE_BLOB,SQLITE_NULL)注意:如果對該列使用了不同與該列本身類型適合的資料讀取方法,得到的數值將是轉換過的結果。4. 得到資料行中某個列的資料的類型  int sqlite3_column_type(sqlite3_stmt*, int iCol);傳回值:SQLITE_INTEGER,SQLITE_FLOAT,SQLITE_TEXT,SQLITE_BLOB,SQLITE_NULL使用的方法和sqlite3_column_xxx()函數類似。//////////////////////////////////////Sqlite 資料庫檔案的產生MAC 上有許多應用程式都可以用來產生它,有 UI 介面很方便。但如果不想另外安裝軟體,MAC 系統也內建 sqlite3 的元件,可由 console 來建立。首先我們先開啟任何一款文書編輯軟體,以 sql 語法來手動建立,並存成 data.sql。1BEGIN TRANSACTION;2CREATE TABLE ‘Info‘ (_id INTEGER PRIMARY KEY, ‘Name‘ TEXT, ‘Tel‘ TEXT, ‘Address‘ TEXT);3INSERT INTO ‘Info‘ VALUES(1,‘Richie‘,‘1234567‘,‘台中市‘);4INSERT INTO ‘Info‘ VALUES(2,‘Eric‘,‘7654321‘,‘台北市‘);5INSERT INTO ‘Info‘ VALUES(3,‘Andy‘,‘1234321‘,‘高雄市‘);6COMMIT;然後在 console 下達以下指令 來產生 data.rdb 這個 sqlite file1sqlite3 data.rdb < data.sqliOS 專案使用 Sqlite 資料庫先將剛才產生的資料庫加入專案中,然後在專案中加入 libsqlite3.0.dylib。接下來開始撰寫程式碼了,xxxAppDelegate.h 必須 import sqlite3.h,並宣告一個 sqlite3 結構。1#import "sqlite3.h"2  3@interface xxxAppDelegate : NSObject <UIApplicationDelegate>4{5    sqlite3* database;6}在 xxxAppDelegate.m 的 didFinishLaunchingWithOptions 函式 開始加入相關程式碼1- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions2{3    // 檢查資料庫是否存在,不存在時則 copy4    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];5    NSString *file = [path stringByAppendingPathComponent:@"data.rdb"];6    if ([[NSFileManager defaultManager] fileExistsAtPath:file] == FALSE)7    {8        NSString *fromFile = [[NSBundle mainBundle] pathForResource:@"data.rdb" ofType:nil];9        [[NSFileManager defaultManager] copyItemAtPath:fromFile toPath:file error:nil];10    }11    // open12    if (sqlite3_open([file UTF8String], &database) != SQLITE_OK)13        NSAssert1(0, @"Failed to open database with message ‘%s‘.", sqlite3_errmsg(database));14  15    self.window.rootViewController = self.viewController;16    [self.window makeKeyAndVisible];17    return YES;18}19  20- (void)dealloc21{22    sqlite3_close(database);23    [super dealloc];24}簡 單說明一下,將 data.rdb 加入專案中後,該資料庫會出現在 app 套件內,但每個 app 就只有專屬 Documents 目錄可以讀寫。所以必須判斷 Documents 目錄下該檔案是否存在,如果不存在則 copy 過去該目錄後再 open 資料庫。至於為什麼做判斷?為什麼不每次都 copy 過去即可?因為如果不希望該資料庫在每次 app 版本更新後,都會被覆蓋掉,就得做檔案存在與否的判斷。讀取資料庫有成功 open 資料庫之後,就可以開始進行讀寫了。讀取資料庫的方法,其實也是很簡單,只要熟悉 SQL 語法,應該就沒什麼問題了。1NSString *sql = [NSString stringWithFormat:@"SELECT * FROM Event "];2sqlite3_stmt *statement;3if (sqlite3_prepare_v2(database, 1, -1, &statement, NULL) == SQLITE_OK)4{5    while (sqlite3_step(statement) == SQLITE_ROW)6    {7        NSString *strValue = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)];8        int intValue = sqlite3_column_int(statement, 1);9    }10}11sqlite3_finalize(statement);其中必須注意的是 sqlite3_column_text, sqlite3_column_int 負責取得資料,必須指定是哪個 column index。執行 SQL 命令上述是 SELECT 的用法,但是如果需要做 INSERT, DELETE, UPDATE 等動作時,則更是簡單,只需以下指令即可。1char *errMsg;2NSString *sql = [NSString stringWithFormat:@"CREATE TABLE ‘Info‘ (_id INTEGER PRIMARY KEY, ‘Name‘ TEXT, ‘Tel‘ TEXT, ‘Address‘ TEXT)"];3sqlite3_exec(database, 1, nil, nil, &errMsg);

  

ios資料庫操作SQLite

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.