I am working on an offline-mode iPhone application in which the first time data comes from the server in JSON format, I parse this data, store it into an mutable array, and then insert these array values into a sqlite database, but only one value or the last value is inserted.
Here is my code for insertion:
-(void)insertData {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:@"paddleEight.sqlite"];
NSLog(@"The Database Path is---> %@", databasePath);
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
int i;
sqlite3_stmt *addStmt;
NSString* sSqlSelect = [NSString stringWithFormat:@"insert into GalleryTabel(depth,imageUrl)VALUES(?,?);"];
for (i = 1; i < [self.propertiesArray count]; i++)
{
if(sqlite3_prepare_v2(database, [sSqlSelect UTF8String], -1, &addStmt, NULL) == SQLITE_OK)
{
sqlite3_bind_text(addStmt, 1, [[[[[self.propertiesArray objectAtIndex:i]objectForKey:@"images"]objectForKey:@"primary"]objectForKey:@"type"] UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [[[[[self.propertiesArray objectAtIndex:i]objectForKey:@"images"]objectForKey:@"primary"]objectForKey:@"location"] UTF8String],-1,SQLITE_TRANSIENT);
}
}
if(sqlite3_step(addStmt)==SQLITE_DONE)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add Record" message:@"Contact Added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"record" message:@"record not created" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
}
}
Any help is highly appreciated. Thanks in Advanced:
You prepare statement multiple times, but executing it only once.
You should prepare statement once (in you case you’re using same SQL instruction), then bind parameters and execute statement for each array element instead.