FMDB lastinsertRowID始终为0 [英] FMDB lastinsertRowID always 0

查看:108
本文介绍了FMDB lastinsertRowID始终为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.

我已经在我的应用程序中实现了FMDB.我正试图以此来从我的一个数据库中获取最后一行ID

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];
        }
    }

我的问题是lastId始终为0,尽管数据库中当前有3个条目. 任何人都不知道为什么会这样吗?

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?

这样创建数据库:

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

推荐答案

lastInsertRowId适用于特定的连接. 您正在使用的连接刚刚打开,因此没有插入的行ID.

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

(lastInsertRowId的目的是允许您的应用知道刚刚被INSERT编辑的记录的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)

这篇关于FMDB lastinsertRowID始终为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆