SQLite没有在iphone应用程序中获取最后插入的行ID

时间:2014-07-09 04:46:09

标签: ios objective-c sqlite

我想从SQLite表中的最后一个插入值中获取id。我用以下方法来实现这一点。它没有得到价值。

NSString *insertSQL = [NSString stringWithFormat:
                                   @"INSERT INTO beacons (beacon_id, vendor_name, enter_message, enter_image, vendor_image, time_interval, received_date, uuid, major, minor) VALUES (\'%@\', \'%@\', \'%@\', \'%@\', \'%@\',%d, \'%@\', \'%@\', %d, %d)",
                                   id, vendorName, sampleMessage, entryImage, thumbnail, [interval intValue], date, uuid, [majorId intValue], [minorId intValue]];

            const char *insert_stmt = [insertSQL UTF8String];
            sqlite3_prepare_v2(_beaconDB, insert_stmt,
                               -1, &statement, NULL);
            long long lastRowId = sqlite3_last_insert_rowid(_beaconDB);
            NSString *rowId = [NSString stringWithFormat:@"%d", (int)lastRowId];
            [identity insertObject:rowId atIndex:i];
            if (sqlite3_step(statement) == SQLITE_DONE)
            {
                NSLog(@"Successfully saved");
            }

在上面的代码中,值已成功插入数据库表。但是最后插入的值的唯一ID不会返回。

提前致谢。

1 个答案:

答案 0 :(得分:2)

在插入sqlite3_step行后,您需要获取最后一行ID

NSString *insertSQL = [NSString stringWithFormat:
                               @"INSERT INTO beacons (beacon_id, vendor_name, enter_message, enter_image, vendor_image, time_interval, received_date, uuid, major, minor) VALUES (\'%@\', \'%@\', \'%@\', \'%@\', \'%@\',%d, \'%@\', \'%@\', %d, %d)",
                               id, vendorName, sampleMessage, entryImage, thumbnail, [interval intValue], date, uuid, [majorId intValue], [minorId intValue]];

const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_beaconDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
    NSLog(@"Successfully saved");
    long long lastRowId = sqlite3_last_insert_rowid(_beaconDB);
    NSString *rowId = [NSString stringWithFormat:@"%d", (int)lastRowId];
    [identity insertObject:rowId atIndex:i];
}

仅供参考 - 您还需要进行更多错误检查,并且在完成后需要清理准备好的语句。