標籤:
我在做app收藏時, 發現我的資料有的是字典, 字典怎麼向資料庫中儲存呢? 就看了好多部落格, 字典應該利用資料庫中的bold類型來儲存,可是添加到資料庫之後,讀取不出來, 為此傷透了腦筋,為瞭解決這個問題, 花費了好時間.
以前認為bold類型就是用來存放二進位的,可以存放圖片等, 而我的資料存到資料庫中的確是二進位,所以讀的時候全是二進位, 以致不能轉換成字典。後來發現我儲存資料的方法就是錯的, bold類型不僅可以放二進位也可以放資料,簡直顛覆了我對bold類型的看法,BLOB,只是一個資料區塊,完全按照輸入存放,並不是只能存放二進位。
儲存字典(向資料庫中寫入):
先將字典轉為NSData類型, 再往資料庫中儲存, 特別注意的是, NSData 資料不能使用 sql 語句插入,因為要向資料庫中寫入blob類型的位元據,還要寫入資料的長度bytes, 所以在寫sql語句時不要插入blob類型的資料,不多說,直接上例子:
sqlite3_stmt *stmt = nil;// NSDictionary 轉 NSDataNSData *data = [NSJSONSerialization dataWithJSONObject:[[List initWithList:list] objectForKey:@"cover_image"] options:NSJSONWritingPrettyPrinted error:nil];// 添加其他欄位可以用這個insert 方法 NSString *sqlstr = [NSString stringWithFormat:@"insert into hjl_list(Id, title, actual_count, collectors_count) values(‘%@‘, ‘%@‘, ‘%@‘, ‘%@‘)", list.Id, list.title, list.actual_count, list.collectors_count];//sql的update語句,為了寫入 blob類型的資料NSString *sqlstr_data = [NSString stringWithFormat:@"update hjl_list set cover_img=? where Id=‘%@‘", list.Id]; int result = sqlite3_exec(db, [sqlstr UTF8String], nil, nil, nil);// 執行 update 語句int result2 = sqlite3_prepare(db, [sqlstr_data UTF8String], -1, &stmt, nil);if (result == SQLITE_OK && result2 == SQLITE_OK) { // 使用 sqlite3_bind_blob64 語句用綁定的方式插入資料,查詢的時候 bytes 才正確 sqlite3_bind_blob64(stmt, 1, [data bytes], [data length], nil); if (sqlite3_step(stmt) == SQLITE_DONE) { NSLog(@"添加成功"); } return YES; } NSLog(@"%@ 失敗",sqlstr); return NO;
讀取資料(從資料庫中讀取):
sqlite3 *db = [DB openDataBase]; sqlite3_stmt *stmt = nil; NSString *sqlstr = [NSString stringWithFormat:@"select * from hjl_list"]; int result = sqlite3_prepare(db, [sqlstr UTF8String], -1, &stmt, nil); if (result == SQLITE_OK) { while (sqlite3_step(stmt) == SQLITE_ROW) { const void *op = sqlite3_column_blob(stmt, 4); int size = sqlite3_column_bytes(stmt, 4); NSData *data = [NSData dataWithBytes:op length:size];// 這裡的dic就是從資料庫中讀取的字典 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; }
IOS中sqlite資料庫利用bold類型儲存與讀取字典