user973984
user973984

Reputation: 2824

How to obtain the Primary Key from a newly created record in SQLite3?

I'm inserting a record with code similar to that below. After the insert, how would I obtain the Primary Key field value from the newly created record?

  NSString *sql1 = [NSString stringWithFormat:@"INSERT INTO mySets (myimage) VALUES ('4')"];
    const char *sqlstring = [sql1 UTF8String];
        if (sqlite3_prepare_v2(appDelegate.myDB, sqlstring, -1, &update_statement, NULL) == SQLITE_OK) {
            int success = sqlite3_step(update_statement);
            if (success != SQLITE_ERROR) {
                int createdSet = sqlite3_column_int(update_statement,0 );
            }
        }

Upvotes: 0

Views: 465

Answers (1)

bryanmac
bryanmac

Reputation: 39296

sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);

http://www.sqlite.org/c3ref/last_insert_rowid.html

You may also want to check sqlite3_errormsg:

if (sqlite3_step(statement) != SQLITE_DONE)
{
    NSLog(@"error: %@", sqlite3_errmsg(_db));
}

Upvotes: 1

Related Questions