IOS開發(94)之SQLite資料庫

來源:互聯網
上載者:User

SQLite是MySQL的簡化版,更多的運用與行動裝置或小型裝置上。SQLite的優點是具有可移植性,它不需要伺服器就能運行,同時,它也存在一些缺陷,首先,沒有提供簡單的資料庫建立方式,必須手工建立資料庫,其次,SQLite沒有物件導向介面,必須使用依賴於C語言代碼的API。相對於OC,這套API既不那麼優雅,也更難使用。當相比於用檔案進行儲存,還是更推薦使用SQLite進行資料存放區。

 


下面來看下如何使用SQLite

 


工程目錄如下:

 

首先建立一個Single View Application工程,命名為SQLite3Test,然後開啟ViewController.xib檔案,布局如下,並設定三個UITextField的tag分別為1、2、3

 

設定tag的地方在屬性選取器中(xcode右邊)

 

 
 

 

然後在ViewController.h檔案中聲明如下:


[cpp]
<span style="font-family:Comic Sans MS;font-size:18px;">#import <UIKit/UIKit.h> 
@interface ViewController : UIViewController 
@property(copy,nonatomic) NSString *databaseFilePath; 
//這個方法定義的是當應用程式退到後台時將執行的方法,按下home鍵執行(通知中樞來調度) 
-(void)applicationWillResignActive:(NSNotification *)notification; 
//當通過鍵盤在UITextField中輸入完畢後,點擊螢幕空白地區關閉鍵盤的操作 
-(IBAction)backgroundTapped:(id)sender; 
@end</span> 

 

接下來看下.m檔案的具體實現,就不一一介紹了,在代碼中會有注釋

在開始寫代碼前,要匯入SQLite支援包 libsqlite3.dylib(具體做法就不詳述了)

上代碼:


[cpp]
#import "ViewController.h" 
#import "sqlite3.h" 
//資料庫檔案的名字 
#define kDatabaseName @"database.sqlite3" 
 
@interfaceViewController () 
 
@end 
 
@implementation ViewController 
 
@synthesize databaseFilePath; 
 
- (void)viewDidLoad 

    [superviewDidLoad]; 
     
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentDirectory = [path objectAtIndex:0]; 
    //指定資料庫檔案的路徑 
    self.databaseFilePath = [documentDirectory stringByAppendingPathComponent:kDatabaseName]; 
     
    //開啟資料庫 
    sqlite3 *database; 
    //[self.databaseFilePath UTF8String];將OC字串裝換成C字串 
    if (sqlite3_open([self.databaseFilePathUTF8String], &database) != SQLITE_OK) { 
        //關閉資料庫 
        sqlite3_close(database); 
        NSAssert(0,@"資料庫開啟失敗"); 
    } 
         
    //建立表格 
    NSString *createSql = @"CREATE TABLE IF NOT EXISTS STUDENT (TAG INTEGER PRIMARY KEY ,FIELD_DATA TEXT);"; 
    //若發生錯誤,則錯誤資訊存在該字串中 
    char *errorMsg; 
     
    //sqlite3_exec這個方法可以執行那些沒有返回結果的操作,例如建立、插入、刪除等,這個函數包含了sqlite3_prepare這個函數的操作,目的是將UTF-8格式的SQL語句轉換為編譯後的語句 
    if (sqlite3_exec(database, [createSql UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK) { 
        sqlite3_close(database); 
        NSAssert(0,@"建立表錯誤:%s", errorMsg); 
    } 
     
    //查詢資料庫 
    NSString *querySql = @"SELECT * FROM STUDENT ORDER BY TAG"; 
    //語句控制代碼 
    sqlite3_stmt *statament; 
    //sqlite3_prepare_v2的作用是將UTF-8格式的SQL語句轉換為編譯後的語句,並返回指向該語句的指標 
    if (sqlite3_prepare_v2(database, [querySql UTF8String], -1, &statament, nil) == SQLITE_OK) { 
        //sqlite3_step的作用是在編譯後的語句中向前移動一條記錄,SQLITE_ROW代表一行 
        while (sqlite3_step(statament) == SQLITE_ROW) { 
            //返回當前這條記錄中的一個int類型欄位的值,下面sqlite3_column_text返回一個字串類型的值,後面的數字對應每一列 
            int tag = sqlite3_column_int(statament, 1); 
            char *rowData = (char *)sqlite3_column_text(statament, 2); 
            //如果要得到一個NSString字串,可以採用如下方法 
            //NSString *str = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statament, 1)]; 
             
            //通過tag得到UI控制項,類似Android中的findViewById(id) 
            UITextField *textField = (UITextField *)[self.viewviewWithTag:tag]; 
             
            //[[NSString alloc]initWithUTF8String:rowData] 將C字串轉換成OC字串 
            textField.text = [[NSStringalloc]initWithUTF8String:rowData]; 
        } 
        //刪除編譯後的語句 
        sqlite3_finalize(statament); 
    } 
    sqlite3_close(database); 
     
    //註冊通知,當程式將要退到後台時執行applicationWillResignActive方法(在.h中定義) 
    UIApplication *application = [UIApplicationsharedApplication]; 
    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotificationobject:application]; 

 
- (void)viewDidUnload 

    [superviewDidUnload]; 
    // Release any retained subviews of the main view. 

 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 

    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 

 
//按下Home鍵程式將要進入後台前儲存UITextField中的資料 
-(void)applicationWillResignActive:(NSNotification *)notification 

    sqlite3 *database; 
    if (sqlite3_open([self.databaseFilePathUTF8String], &database) != SQLITE_OK) { 
        NSAssert(0,@"開啟資料庫錯誤"); 
        sqlite3_close(database); 
    } 
     
    for (int i = 1; i <= 3; i++) { 
        UITextField *textField = (UITextField *)[self.viewviewWithTag:i]; 
         
        //插入資料 
        char *update = "INSERT OR REPLACE INTO STUDENT VALUES (?,?)"; 
        sqlite3_stmt *statement; 
        if (sqlite3_prepare_v2(database, update, -1, &statement, nil) == SQLITE_OK) { 
            //將值儲存到指定的列 
            sqlite3_bind_int(statement, 1, i); 
             
            //第四個參數代表第三個參數中需要傳遞的長度。對於C字串來說,-1表示傳遞全部字串。第五個參數是一個回呼函數,比如執行後做記憶體清除工作。 
            sqlite3_bind_text(statement, 2, [textField.textUTF8String], -1, NULL); 
        } 
         
        char *errorMsg = NULL; 
        //SQLITE_DONE代表更新資料庫是否完成 
        if (sqlite3_step(statement) != SQLITE_DONE) { 
            NSAssert(0,@"更新資料出錯:%s",errorMsg); 
        } 
        sqlite3_finalize(statement); 
    } 
     
    sqlite3_close(database); 

 
-(IBAction)backgroundTapped:(id)sender 

    /*當通過鍵盤在UITextField中輸入完畢後,點擊螢幕空白地區關閉鍵盤的操作
     設定步驟是開啟.xib檔案選中整個視圖,然後將屬性選取器中的class由UIView改成UIControl,然後在事件選取器中選擇Touch Down事件並連線到.h檔案中的backgroundTapped方法
     */ 
    for (int i = 1; i <= 3; i ++) { 
        UITextField *textField = (UITextField *)[self.viewviewWithTag:i]; 
        [textField resignFirstResponder]; 
    } 

 
@end 


最後運行效果如下,輸入資訊後按下Home鍵,然後再進入應用,可以看到資料在每次退出前都儲存了,再次進入則從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.