iOS學習筆記16-資料庫SQLite

來源:互聯網
上載者:User

iOS學習筆記16-資料庫SQLite
一、資料庫

在項目開發中,通常都需要對資料進行離線緩衝的處理,如新聞資料的離線緩衝等。離線緩衝一般都是把資料儲存到項目的沙箱中。有以下幾種方式:
1. 歸檔:NSKeyedArchiver
2. 喜好設定:NSUserDefaults
3. plist儲存:writeToFile

上述的使用可以參考iOS學習筆記15-序列化、喜好設定和歸檔,但上述三種方法都有一個致命的缺點,那就是都無法儲存大批量的資料,有效能的問題,在這個時候就是使用資料庫的時候。

資料庫(Database)是按照資料結構來組織、儲存和管理資料的倉庫,用於儲存管理大量的資料,可以高效的儲存大批量資料,也可以高效的讀取大批量資料,功能強大。

資料庫的儲存結構和excel很像,以表(table)為單位。表由多個欄位(列、屬性、column)組成,表裡面的每一行資料稱為記錄,但又不是簡單的表格,還有表與表之間的關係,也就是現在主流的關係型資料庫。

二、SQLite介紹

SQLite是一款輕型的嵌入式資料庫,安卓和iOS開發使用的都是SQLite資料庫。
它的特點:
1. 它佔用資源非常的低,在嵌入式裝置中,可能只需要幾百K的記憶體就夠了。
2. 它的處理速度比MySQL、PostgreSQL這兩款著名的資料庫都還快。
3. 它是C語言架構的,跨平台性強。

我們現在已經到了SQLite3時代了,後面的3是版本,現在我們就開始來使用它吧。

三、SQLite3的使用一般常用的資料庫操作有:【本章就以這5個步驟進行講解】建立資料庫建立表向表插入資料從表中讀取資料關閉資料庫

要在iOS中使用SQLite3,需要在Xcode匯入libsqlite3的庫

上面兩個其中一個都可以,然後我們還需要在項目中添加標頭檔和定義一個資料庫控制代碼,這個資料庫控制代碼控制資料庫的所有操作。

1. 開啟資料庫使用的C語言函數如下:
/* 開啟資料庫 */int sqlite3_open(  const char *filename,   /* 資料庫路徑(UTF-8) */  sqlite3 **pDb           /* 返回的資料庫控制代碼 */);
下面是執行個體:
/* 開啟資料庫 */- (void)openDatabase:(NSString *)dbname{    //產生沙箱檔案路徑    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];    NSString *filePath = [directory stringByAppendingPathComponent:dbname];    //開啟資料庫,如果資料庫存在直接開啟,如果資料庫不存在,建立並開啟    int result = sqlite3_open(filePath.UTF8String, &_database);    if (result == SQLITE_OK) {        NSLog(@"Open Database Success");    } else {        NSLog(@"Open Database Fail");    }}
2. 執行沒有傳回值得SQL語句使用的C語言函數:
/* 執行沒有返回的SQL語句 */int sqlite3_exec(  sqlite3 *db,                               /* 資料庫控制代碼 */  const char *sql,                           /* SQL語句(UTF-8) */  int (*callback)(void*,int,char**,char**),  /* 回調的C函數指標 */  void *arg,                                 /* 回呼函數的第一個參數 */  char **errmsg                              /* 返回的錯誤資訊 */);
使用執行個體:
/* 執行沒有傳回值的SQL語句 */- (void)executeNonQuery:(NSString *)sql{    if (!_database) {        return;    }    char *error;    //執行沒有傳回值的SQL語句    int result = sqlite3_exec(_database, sql.UTF8String, NULL, NULL, &error);    if (result == SQLITE_OK) {        NSLog(@"Execute SQL Query Success");    } else {        NSLog(@"Execute SQL Query Fail error : %s",error);    }}
3.執行有傳回值的SQL語句使用的C語言函數:
/* 執行有返回結果的SQL語句 */int sqlite3_prepare_v2(  sqlite3 *db,            /* 資料庫控制代碼 */  const char *zSql,       /* SQL語句(UTF-8) */  int nByte,              /* SQL語句最大長度,-1表示SQL支援的最大長度 */  sqlite3_stmt **ppStmt,  /* 返回的查詢結果 */  const char **pzTail     /* 返回的失敗資訊*/);
既然有返回結果,怎麼處理返回結果,也有一些C語言函數:
#pragma mark - 定位記錄的方法/* 在查詢結果中定位到一條記錄 */int sqlite3_step(sqlite3_stmt *stmt);/* 擷取當前定位記錄的欄位名稱數目 */int sqlite3_column_count(sqlite3_stmt *stmt);/* 擷取當前定位記錄的第幾個欄位名稱 */const char * sqlite3_column_name(sqlite3_stmt *stmt, int iCol);# pragma mark - 擷取欄位值的方法/* 擷取位元據 */const void * sqlite3_column_blob(sqlite3_stmt *stmt, int iCol);/* 擷取浮點型資料 */double sqlite3_column_double(sqlite3_stmt *stmt, int iCol);/* 擷取整數資料 */int sqlite3_column_int(sqlite3_stmt *stmt, int iCol);/* 擷取文本資料 */const unsigned char * sqlite3_column_text(sqlite3_stmt *stmt, int iCol);
使用執行個體:
/* 執行有傳回值的SQL語句 */- (NSArray *)executeQuery:(NSString *)sql{    if (!_database) {        return nil;    }    NSMutableArray *array = [NSMutableArray array];    sqlite3_stmt *stmt; //儲存查詢結果    //執行SQL語句,返回結果儲存在stmt中    int result = sqlite3_prepare_v2(_database, sql.UTF8String, -1, &stmt, NULL);    if (result == SQLITE_OK) {        //每次從stmt中擷取一條記錄,成功返回SQLITE_ROW,直到全部擷取完成,就會返回SQLITE_DONE        while( SQLITE_ROW == sqlite3_step(stmt)) {            //擷取一條記錄有多少列            int columnCount = sqlite3_column_count(stmt);            //儲存一條記錄為一個字典            NSMutableDictionary *dict = [NSMutableDictionary dictionary];            for (int i = 0; i < columnCount; i++) {                //擷取第i列的欄位名稱                const char *name  = sqlite3_column_name(stmt, i);                //擷取第i列的欄位值                const unsigned char *value = sqlite3_column_text(stmt, i);                //儲存進字典                NSString *nameStr = [NSString stringWithUTF8String:name];                NSString *valueStr = [NSString stringWithUTF8String:(const char *)value];                dict[nameStr] = valueStr;            }            [array addObject:dict];//添加目前記錄的字典儲存        }        sqlite3_finalize(stmt);//stmt需要手動釋放記憶體        stmt = NULL;        NSLog(@"Query Stmt Success");        return array;    }    NSLog(@"Query Stmt Fail");    return nil;}
4. 關閉資料庫使用的C語言函數:
/* 關閉資料庫 */int sqlite3_close(sqlite3 *db);
使用執行個體:
/* 關閉資料庫 */- (void)closeDatabase{    //關閉資料庫    int result = sqlite3_close(_database);    if (result == SQLITE_OK) {        NSLog(@"Close Database Success");        _database = NULL;    } else {        NSLog(@"Close Database Fail");    }}
四、SQLite結合SQL語句

除了使用libsqlite庫裡的C語言函數還無法完成對資料庫操作,還需要使用到SQL語句,就是一門控制資料庫的語言【一個大知識】。

這裡就簡單列出一些常用的SQL語句:建立表:
create table 表名稱(欄位1,欄位2,……,欄位n,[表級約束])[TYPE=表類型]; 插入記錄:
insert into 表名(欄位1,……,欄位n) values (值1,……,值n); 刪除記錄:
delete from 表名 where 條件運算式; 修改記錄:
update 表名 set 欄位名1=值1,……,欄位名n=值n where 條件運算式; 查看記錄:
select 欄位1,……,欄位n from 表名 where 條件運算式;下面是結合SQL陳述式完成資料庫操作,使用到的是上面定義的方法:
/* 結合SQL語句,操作資料庫 */- (void)sqlite3Test{    //開啟SQlite資料庫    [self openDatabase:@"sqlite3_database.db"];    //在資料庫中建立表    [self executeNonQuery:@"create table mytable(num varchar(7),name varchar(7),sex char(1),primary key(num));"];    //在表中插入記錄    [self executeNonQuery:@"insert into mytable(num,name,sex) values (0,'liuting','m');"];    [self executeNonQuery:@"insert into mytable(num,name,sex) values (1,'zhangsan','f');"];    [self executeNonQuery:@"insert into mytable(num,name,sex) values (2,'lisi','m');"];    [self executeNonQuery:@"insert into mytable(num,name,sex) values (3,'wangwu','f');"];    [self executeNonQuery:@"insert into mytable(num,name,sex) values (4,'xiaoming','m');"];    //讀取資料庫的表中資料    NSArray* result = [self executeQuery:@"select num,name,sex from mytable;"];    if (result) {        for (NSDictionary *row in result) {            NSString *num = row[@"num"];            NSString *name = row[@"name"];            NSString *sex = row[@"sex"];            NSLog(@"Read Database : num=%@, name=%@, sex=%@",num,name,sex);        }    }    [self closeDatabase];}/* 修改一下,把原來存在的資料庫檔案刪除掉,再建立並開啟資料庫 */- (void)openDatabase:(NSString *)dbname{    //產生沙箱檔案路徑    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];    NSString *filePath = [directory stringByAppendingPathComponent:dbname];    //判斷該檔案在不在    NSFileManager *manager = [NSFileManager defaultManager];    if ([manager fileExistsAtPath:filePath]){        //檔案存在,就刪除掉        [manager removeItemAtPath:filePath error:NULL];    }    //開啟資料庫,保持sqlite3資料庫物件_database,傳回值判別是否開啟成功    int result = sqlite3_open(filePath.UTF8String, &_database);    if (result == SQLITE_OK) {        NSLog(@"Open Database Success");    } else {        NSLog(@"Open Database Fail");    }}

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.