iOS FMDB 更新二進位圖片資料

來源:互聯網
上載者:User

拋棄了sqlite的標準操作,我使用的實FMDB--一個對基本sqlite文法進行封裝後便於資料訪問與C# ado.net有點類似。

使用FMDB很方便的實現了通過資料庫欄位名而不是欄位索引)資料的讀取,插入,更新,刪除。但是我在更新圖片時發現通過格式化字元@ “%@”,data/*NSData*/)傳入的位元據更新到資料庫後不能顯示圖片。如果使用的時INSERT 方法能將圖片資訊正確儲存到資料庫重,因為在FMDB中處理INSERT時會調用到下面的方法。

 
  1. - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt { 
  2.      
  3.     if ((!obj) || ((NSNull *)obj == [NSNull null])) { 
  4.         sqlite3_bind_null(pStmt, idx); 
  5.     } 
  6.      
  7.     // FIXME - someday check the return codes on these binds. 
  8.     else if ([obj isKindOfClass:[NSData class]]) { 
  9.         sqlite3_bind_blob(pStmt, idx, [obj bytes], (int)[obj length], SQLITE_STATIC); 
  10.     } ...... 

通過這句標準sqlite語句 才能有效將二進位資訊儲存到資料庫 sqlite3_bind_blob(pStmt, idx, [obj bytes], (int)[obj length], SQLITE_STATIC);

後 來我測試了幾次,如果使用UPDATE語句是不可能調用上面的方法的,那麼需要怎樣才能更新圖片等二進位資訊呢?可能對於FMDB我還沒完全瞭解,不知道有沒有處理更新位元據的方法,我也沒時間去找了,於是就在FMDB源碼中添加了一個方法,用來儲存位元據)如下:

 
  1. - (BOOL)executeUpdate:(NSString*)sql imageData:(NSData*)imageData{ 
  2.      
  3.     if(!imageData || [imageData length] < 4) 
  4.         return  NO; 
  5.      
  6.     sqlite3_stmt *statement; 
  7.     int success = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &statement, NULL); 
  8.     if (success != SQLITE_OK) { 
  9.         //NSLog(@"Error: failed to update picture"); 
  10.         return NO; 
  11.     } 
  12.      
  13.     sqlite3_bind_blob(statement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT); 
  14.      
  15.     success = sqlite3_step(statement); 
  16.     sqlite3_finalize(statement); 
  17.      
  18.     if (success != SQLITE_DONE) { 
  19.         //NSLog(@"Error: failed to update picture into the database "); 
  20.         return NO; 
  21.     } 
  22.      
  23.     return  YES; 

其實就是自己添加了一個標準的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.