iOS FMDB 更新二進(jìn)制圖片數(shù)據(jù)
拋棄了sqlite的標(biāo)準(zhǔn)操作,我使用的實(shí)FMDB--一個(gè)對(duì)基本sqlite語法進(jìn)行封裝后便于數(shù)據(jù)訪問與C# ado.net有點(diǎn)類似。
使用FMDB很方便的實(shí)現(xiàn)了(通過數(shù)據(jù)庫字段名而不是字段索引)數(shù)據(jù)的讀取,插入,更新,刪除。但是我在更新圖片時(shí)發(fā)現(xiàn)通過格式化字符(@ “%@”,data/*NSData*/)傳入的二進(jìn)制數(shù)據(jù)更新到數(shù)據(jù)庫后不能顯示圖片。如果使用的時(shí)INSERT 方法能將圖片信息正確保存到數(shù)據(jù)庫重,因?yàn)樵贔MDB中處理INSERT時(shí)會(huì)調(diào)用到下面的方法。
- - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
- if ((!obj) || ((NSNull *)obj == [NSNull null])) {
- sqlite3_bind_null(pStmt, idx);
- }
- // FIXME - someday check the return codes on these binds.
- else if ([obj isKindOfClass:[NSData class]]) {
- sqlite3_bind_blob(pStmt, idx, [obj bytes], (int)[obj length], SQLITE_STATIC);
- } ......
通過這句標(biāo)準(zhǔn)sqlite語句 才能有效的將二進(jìn)制信息保存到數(shù)據(jù)庫 sqlite3_bind_blob(pStmt, idx, [obj bytes], (int)[obj length], SQLITE_STATIC);
后 來我測(cè)試了幾次,如果使用UPDATE語句是不可能調(diào)用上面的方法的,那么需要怎樣才能更新圖片等二進(jìn)制信息呢?(可能對(duì)于FMDB我還沒完全了解,不知道有沒有處理更新二進(jìn)制數(shù)據(jù)的方法,我也沒時(shí)間去找了,于是就在FMDB源碼中添加了一個(gè)方法,用來保存二進(jìn)制數(shù)據(jù))如下:
- - (BOOL)executeUpdate:(NSString*)sql imageData:(NSData*)imageData{
- if(!imageData || [imageData length] < 4)
- return NO;
- sqlite3_stmt *statement;
- int success = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &statement, NULL);
- if (success != SQLITE_OK) {
- //NSLog(@"Error: failed to update picture");
- return NO;
- }
- sqlite3_bind_blob(statement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
- success = sqlite3_step(statement);
- sqlite3_finalize(statement);
- if (success != SQLITE_DONE) {
- //NSLog(@"Error: failed to update picture into the database ");
- return NO;
- }
- return YES;
- }
其實(shí)就是自己添加了一個(gè)標(biāo)準(zhǔn)的sqlite更新方法,希望能給大家?guī)韼椭?,如果有更好的方法,不令賜教。