FMDatabase iOS INSERT问题

时间:2012-01-25 11:55:42

标签: ios sqlite insert fmdb

我正在使用数据库创建应用程序。对于模态,我使用FMDatabase类。现在我必须在两个表中插入一些新数据: -project(id_proj主键autoince unique,name,baseImage) -imagesforpro(id_img primkey autoincr unique,smallimage,largeimage,id_proj) 我有一个方法-(void)addProject:(Project*)proj,我传递了一个Project对象。 然后我必须将projectName和baseImage插入到项目表中,然后提取我刚插入的记录的id_proj,并将small和larges图像插入到imagesforpro表中。如何记住最后插入记录的id_proj(自动增量)?而且,如何使用INSERT?我正确使用它吗?如何正确地将NSData放入数据库?谢谢。以下是我到目前为止的情况:

-(void)addProject:(Project*)proj
{
    [db open];
    NSData *bmdata=UIImagePNGRepresentation(proj.baseImage);
    if (proj==nil) {
        NSLog(@"Dead Object");
    }
    NSLog(@" NEW name is %@", proj.projectName);
    //DOESN'T WORK
    //id_proj is autoincrement field that's why I just pass name and base image
   [db executeUpdate:@"INSERT INTO project VALUES (?,?)", [proj.projectName UTF8String], bmdata];
    //sqlite3_last_insert_rowid()
    [db close];
    sqlite3 *dataB;
    int status=sqlite3_open([[self dbPath] UTF8String], &dataB);
    if(status!=SQLITE_OK)
    {

        NSLog(@"Error");
        //exit(1);
    }
    //RETURNS 0(
    int lastindex=sqlite3_last_insert_rowid(dataB);
    NSLog(@"Last inserted index %i", lastindex);
    sqlite3_close(dataB);


    [db open];
    //Add images for the project (another table)
    for(int i=0; i<[proj.largeImages count]; i++)
    {
        UIImage *smallImg=[proj.smallImages objectAtIndex:i];
        UIImage *bigImg=[proj.largeImages objectAtIndex:i];
        NSData *sidata=UIImagePNGRepresentation(smallImg);
        NSData *bidata=UIImagePNGRepresentation(bigImg);
        // Here I have to insert an image and id of the project it refers too
        //How do I find out the last inserted id_proj?
        [db executeUpdate:@"INSERT INTO imagesforpro VALUES (?,?,?)", sidata, bidata, lastindex];
    }


     [db close];


}

0 个答案:

没有答案