views:

3007

answers:

4

hello, I want to insert an image in sqlite3, i have created table using "create table table1(photo blob,name varchar(10));" Now i want to insert an image in to it,so what is syntax for insert image into it? and in another table i want to store location of the image so for second table what is my create table and insert table syntax. Can you plz help me???? And how can i check it whether it is inserted properly or not from command line?

+2  A: 

This question is very close to the one you're asking.

Brad Larson
A: 

why dont you simply save the image on the iphone file system and only save its location info in sqlite?

Raj
ok but then how can i integrate both of them??
A: 

You could get the raw NSData for the image and save that...

NSData *imageData = UIImagePNGRepresentation(image);
Jason
ok its working,in gdb compiler it shows 4 rows repeatatively,but actually i insert only one row why so? can u plz help me??
NSData is represented in gdb as a multipart set of data, but it can be transformed into a NSString object.
Jason
+1  A: 

You can insert an image in sqlite3 by following lines of code.

1)=First prepare SQLite insert Statement

   static sqlite3_stmt *insert_statement; //Declare Insert statement    
    - (void)InsertIntoDatabase{  // start insert method
         const char *sql = "INSERT INTO <yourtable> (<column1>, <BLOBColumnName>) VALUES (? , ?)" ;
           if(sqlite3_prepare_v2(database, sql, -1, &insert_statement, NULL) != SQLITE_OK)
              NSAssert1(0, @"Error while creating insert statement. '%s'", sqlite3_errmsg(database));} 

//For simple integer column**
   sqlite3_bind_int(insert_statement, 1, <value column 1>);

//For image column**
  NSString *webUrl = @"http://yourwebsite/youImage.jpg";        
  UIImage *myImage =  [self GetRawImage:webUrl]; //Get image from method below
                     if(myImage != nil){
                     NSData *imgData = UIImagePNGRepresentation(myImage);
                     sqlite3_bind_blob(insert_statement, 2, [imgData bytes], [imgData length], NULL);
                     }
                     else {
                      sqlite3_bind_blob(insert_statement, 2, nil, -1, NULL);
                     }
    } // end of insert method

2)=Method for Getting Raw Image File.

 - (UIImage *)GetRawImage:(NSString *)imageUrlPath
    {  
    NSURL *imageURL = [NSURL URLWithString:imageUrlPath];  
    NSData *data = [NSData dataWithContentsOfURL:imageURL];  
    UIImage *image = [[UIImage alloc] initWithData:data];   
    return image; 
    }

!Its done so Simple

Khawar