Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FMDB lastinsertRowID always 0

Hya.

I have implemented FMDB in my app. I am trying to get the last row id from one of my databases with this

FMDatabase *bdb=[FMDatabase databaseWithPath:databasePath];
    NSString *str;
    if([bdb open]){
        int lastId=[bdb lastInsertRowId];
        FMResultSet *s = [bdb executeQuery:[NSString stringWithFormat:@"SELECT budget FROM data WHERE ROWID='%d'",lastId]];
        if([s next])
        {
            str= [s stringForColumnIndex:0];
        }
    }

the problem i have is that lastId is always 0 , although there are 3 entries currently in the database. Any1 have any idea why is this happening?

EDIT: the database is created like this:

NSFileManager *filemgr = [NSFileManager defaultManager];
    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];

        if (sqlite3_open(dbpath, &basicDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS DATA (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, BUDGET INTEGER)";

            if (sqlite3_exec(basicDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
               DLog(@"Failed to create table");
            }
           sqlite3_close(basicDB);

        } else {
           DLog(@"Failed to open/create database");
        }
    }
like image 780
s.calin Avatar asked Jul 24 '26 02:07

s.calin


1 Answers

lastInsertRowId works on a specific connection. The connection that you're using has just been opened, so there is no inserted row ID.

(The purpose of lastInsertRowId is to allow your app to know the ID of a record that has just been INSERTed.)

To read data from the last record, use something like this:

SELECT budget FROM data WHERE rowid = (SELECT max(rowid) FROM data)
like image 151
CL. Avatar answered Jul 25 '26 17:07

CL.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!