开发者

iPhone iOS: SQLite3 Not able to get last ID value in Table

开发者 https://www.devze.com 2023-03-30 17:06 出处:网络
I\'ve 开发者_如何学Gobeen trying to figure this out for almost the whole day, and after several attempts, I figured I\'d see if anyone here might have some ideas. Any help is welcome.

I've 开发者_如何学Gobeen trying to figure this out for almost the whole day, and after several attempts, I figured I'd see if anyone here might have some ideas. Any help is welcome.

I have a pretty simple table of ID's and Name's and I would like to get the last ID value in the table.

Although I don't get any compile errors or run-time errors, I'm getting the wrong value for ID. According to SQLiteManager (which can directly check the database) my max ID is 10, however, no matter what I do I simply get a value of 0 for PlayKey.

Here's the definitions:

//CREATE THE Plays TABLE
char *errorMsg;
NSString *createSQL = @"CREATE TABLE IF NOT EXISTS Plays (ID integer PRIMARY KEY AUTOINCREMENT,PlayName text);";
if (sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK){
    sqlite3_close(database);
    NSAssert1(0, @"Error creating table: %s", errorMsg);
}

and here is where I try to get the last ID that was inserted into it:

NSString *query3 = [NSString stringWithFormat:@"SELECT MAX(ID) FROM Plays"];
sqlite3_stmt *statement3;
if (sqlite3_prepare_v2(database, [query3 UTF8String], -1, &statement3, nil) == SQLITE_OK) {
    PlayKey = sqlite3_column_int(statement3, 0);
    NSString* msg4 = [NSString stringWithFormat:@"This worked! The PlayKey was %d", PlayKey];
    NSLog(msg4);
}
if (sqlite3_step(statement3) !=SQLITE_DONE) {NSLog(@"Error inserting to Steps");}

I also tried to do this using a much simpler built in function:

PlayKey = sqlite3_last_insert_rowid(database);

Both these tries result in an incorrect value of 0.


You also can retrieve the last ID of any table through sqlite_sequence. EX-

+(int)getLastLocationId{
    NSString *sqlNsStr = [NSString stringWithFormat:@"SELECT * FROM sqlite_sequence where name='Location'"];
    const char *sql = [sqlNsStr cStringUsingEncoding:NSUTF8StringEncoding];
    int lastrec=0;
    //    if(sqlite3_open([dbPath UTF8String], &masterDB) == SQLITE_OK){
    if (sqlite3_prepare_v2(masterDB, sql, -1, &init_statement, NULL) == SQLITE_OK) {
        while(sqlite3_step(init_statement) == SQLITE_ROW) {
            lastrec = sqlite3_column_int(init_statement, 1);
        }
        sqlite3_reset(init_statement);
    }
    return lastrec;
}


Is this after very first insert? Or you have bunch of records already? ROWID starts with 0, so very first record gets ROWID=0.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号