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.dylib
2,代碼中的操作:
那麼接下來是代碼了。
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,将傳回0
2. 得到目前行中包含的資料個數
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。
2 | CREATE TABLE 'Info' (_id INTEGER PRIMARY KEY, 'Name' TEXT, 'Tel' TEXT, 'Address' TEXT); |
3 | INSERT INTO 'Info' VALUES(1,'Richie','1234567','台中市'); |
4 | INSERT INTO 'Info' VALUES(2,'Eric','7654321','台北市'); |
5 | INSERT INTO 'Info' VALUES(3,'Andy','1234321','高雄市'); |
然後在 console 下達以下指令 來產生 data.rdb 這個 sqlite file
1 | sqlite3 data.rdb < data.sql |
iOS 專案使用 Sqlite 資料庫
先將剛才產生的資料庫加入專案中,然後在專案中加入 libsqlite3.0.dylib。
接下來開始撰寫程式碼了,xxxAppDelegate.h 必須 import sqlite3.h,並宣告一個 sqlite3 結構。
3 | @interface xxxAppDelegate : NSObject <UIApplicationDelegate> |
在 xxxAppDelegate.m 的 didFinishLaunchingWithOptions 函式 開始加入相關程式碼
1 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions |
3 | // 檢查資料庫是否存在,不存在時則 copy |
4 | NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; |
5 | NSString *file = [path stringByAppendingPathComponent:@"data.rdb"]; |
6 | if ([[NSFileManager defaultManager] fileExistsAtPath:file] == FALSE) |
8 | NSString *fromFile = [[NSBundle mainBundle] pathForResource:@"data.rdb" ofType:nil]; |
9 | [[NSFileManager defaultManager] copyItemAtPath:fromFile toPath:file error:nil]; |
12 | if (sqlite3_open([file UTF8String], &database) != SQLITE_OK) |
13 | NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database)); |
15 | self.window.rootViewController = self.viewController; |
16 | [self.window makeKeyAndVisible]; |
22 | sqlite3_close(database); |
簡 單說明一下,將 data.rdb 加入專案中後,該資料庫會出現在 app 套件內,但每個 app 就隻有專屬 Documents 目錄可以讀寫。是以必須判斷 Documents 目錄下該檔案是否存在,如果不存在則 copy 過去該目錄後再 open 資料庫。至於為什麼做判斷?為什麼不每次都 copy 過去即可?因為如果不希望該資料庫在每次 app 版本更新後,都會被覆蓋掉,就得做檔案存在與否的判斷。
讀取資料庫
有成功 open 資料庫之後,就可以開始進行讀寫了。讀取資料庫的方法,其實也是很簡單,隻要熟悉 SQL 語法,應該就沒什麼問題了。
1 | NSString *sql = [NSString stringWithFormat:@"SELECT * FROM Event "]; |
2 | sqlite3_stmt *statement; |
3 | if (sqlite3_prepare_v2(database, 1, -1, &statement, NULL) == SQLITE_OK) |
5 | while (sqlite3_step(statement) == SQLITE_ROW) |
7 | NSString *strValue = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)]; |
8 | int intValue = sqlite3_column_int(statement, 1); |
11 | sqlite3_finalize(statement); |
其中必須注意的是 sqlite3_column_text, sqlite3_column_int 負責取得資料,必須指定是哪個 column index。
執行 SQL 指令
上述是 SELECT 的用法,但是如果需要做 INSERT, DELETE, UPDATE 等動作時,則更是簡單,隻需以下指令即可。
2 | NSString *sql = [NSString stringWithFormat:@"CREATE TABLE 'Info' (_id INTEGER PRIMARY KEY, 'Name' TEXT, 'Tel' TEXT, 'Address' TEXT)"]; |
3 | sqlite3_exec(database, 1, nil , nil , &errMsg); |