2011-03-05 58 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应用程序时,它会提取不良数据。如果你这样做,我想知道答案。