jaynaiphone
jaynaiphone

Reputation:

How do you insert an image into SQLite on the iPhone?

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?

Upvotes: 2

Views: 9108

Answers (3)

Xorsat
Xorsat

Reputation: 2408

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

Upvotes: 3

Jason
Jason

Reputation: 452

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

NSData *imageData = UIImagePNGRepresentation(image);

Upvotes: 1

Raj
Raj

Reputation: 6830

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

Upvotes: 1

Related Questions