FMDB lastinsertRowID always 0

做~自己de王妃 提交于 2020-02-02 06:19:45

问题


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");
        }
    }

回答1:


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)


来源:https://stackoverflow.com/questions/12976670/fmdb-lastinsertrowid-always-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!