0

我正在使用数据库制作应用程序。对于模态,我使用 FMDatabase 类。现在我必须在两个表中插入一些新数据: -project(id_proj primary key autoince unique, name, baseImage) -imagesforpro(id_img primkey autoincr unique, smallimage, largeimage, id_proj) 我有一个方法-(void)addProject:(Project*)proj可以传递一个 Project 对象. 然后我必须将 projectName 和 baseImage 插入到项目表中,然后提取我刚刚插入的记录的 id_proj 并将大小图像插入到 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];


}
4

0 回答 0