2011-03-05 84 views
1

您好我是能夠通過使用下面的代碼將圖像存儲到數據庫.......問題在iphone從數據庫中讀取圖像

-(void)insertimages: (NSData *)image 
{ 
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) 
    { 
     NSUInteger len = [image length]; 
     NSLog(@"data size is %d", len); 

     sqlStatement="insert into messages values(10,?)"; 
     if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
     { 
      //sqlite3_bind_int(compiledStatement, 1, -1); 
      //sqlite3_bind_blob(updateStmt, 3, [imgData bytes], [imgData length], NULL); 
      sqlite3_bind_blob(compiledStatement, 1, [image bytes], [image length], SQLITE_TRANSIENT); 
      //sqlite3_bind_text(compiledStatement, 1, [SMSBody UTF8String],-1,SQLITE_STATIC); 
      if(sqlite3_step(compiledStatement) == SQLITE_DONE) 
      { 
       sqlite3_finalize(compiledStatement);     
      } 

     }  
     sqlite3_close(database);  
    } 
} 

,但現在我的問題是我不能夠從數據庫檢索圖像,並顯示它在uiimageview ...

con任何人請幫助我如何做到這一點。

回答

1

使用下面的方法來讀取數據庫中的圖像數據,並存儲在陣列或


-(void) readImageDataFromDatabase { 
    // Setup the database object 
    sqlite3 *database; 

    // Init the img Array 
    imageArray = [[NSMutableArray alloc] init]; 

    // Open the database from the users filessytem 
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { 
     // Setup the SQL Statement and compile it for faster access 
     const char *sqlStatement = "select * from messages"; 
     sqlite3_stmt *compiledStatement; 
     if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { 
      // Loop through the results and add them to the feeds array 
      while(sqlite3_step(compiledStatement) == SQLITE_ROW) { 
       // Read the data from the result row 
       NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]]; 
]; 
       NSData *imgData = [NSData dataWithContentsOfURL: url]; 

       // Create a new image object with the data from the database 
       iconImage.image=[UIImage imageWithData:imgData]; 

       // Add the img object to the img Array 
       [imageArray addObject:iconImage]; 
      } 
     } 
     // Release the compiled statement from memory 
     sqlite3_finalize(compiledStatement); 

    } 
    sqlite3_close(database); 

} 

+0

嗨,一個很好,但我不存儲圖像的網址。直接保存在數據庫中的圖像,並希望檢索它... – user564963 2011-03-05 10:12:25

+0

@ user564963-嗨,PLZ仔細看看我沒有檢索URL字符串,我檢索URL對象中的圖像數據,並將其傳遞給NSData對象。 – 2011-03-05 10:22:21

0

我試圖做這個一年前字典中的圖像,我寫代碼的圖像保存到sqlite3的db使用osx sdk(我可以讀寫,我甚至可以用ruby將數據存儲在數據庫中,並使用macosx sdk讀取它們)。但是當我將這個確切的代碼移動到iOS應用程序時,它會提取不良數據。如果你這樣做,我想知道答案。