只有最后一个值插入到iPhone上的sqlite数据库中

时间:2012-02-15 11:42:01

标签: iphone objective-c ios sqlite

我正在开发一个离线模式的iPhone应用程序,其中第一次数据来自服务器的JSON格式,我解析这些数据,将其存储到一个可变数组中,然后将这些数组值插入到sqlite数据库中,但只插入一个值或最后一个值。

以下是我的插入代码:

-(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;
    }

  }

}

非常感谢任何帮助。谢谢高级:

2 个答案:

答案 0 :(得分:0)

尝试使用此接受的答案。它显示了如何将数组值保存到数据库Only last value is inserted into sqlite database on iPhone

答案 1 :(得分:0)

您多次准备语句,但只执行一次。 你应该准备一次语句(在你使用相同的SQL指令的情况下),然后为每个数组元素绑定参数和执行语句。