iPhone iOS:SQLite3无法获取表中的最后一个ID值 [英] iPhone iOS: SQLite3 Not able to get last ID value in Table

查看:47
本文介绍了iPhone iOS:SQLite3无法获取表中的最后一个ID值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎整天都在尝试解决这个问题,经过几次尝试,我发现自己会发现这里是否有人有想法.欢迎任何帮助.

I've been 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.

我有一个非常简单的ID和Name表,我想获取表中的最后一个ID值.

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.

尽管我没有得到任何编译错误或运行时错误,但是我得到的ID值错误.根据SQLiteManager(它可以直接检查数据库),我的最大ID是10,但是,无论我做什么,我都只能将PlayKey的值设置为0.

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.

这是定义:

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

这是我尝试获取插入其中的最后一个ID的地方:

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

这两种尝试都会导致错误的值为0.

Both these tries result in an incorrect value of 0.

推荐答案

您还可以通过sqlite_sequence检索任何表的最后一个ID.EX-

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

这篇关于iPhone iOS:SQLite3无法获取表中的最后一个ID值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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