简体   繁体   English

iPhone iOS:SQLite3无法获取表中的最后一个ID值

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

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. 欢迎任何帮助。

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和Name的表格,我想获得表格中的最后一个ID值。

Although I don't get any compile errors or run-time errors, I'm getting the wrong value for ID. 虽然我没有得到任何编译错误或运行时错误,但我得到了错误的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. 根据SQLiteManager(可以直接检查数据库),我的最大ID是10,但是,无论我做什么,我只是为PlayKey获取值0。

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: 这是我尝试获取插入其中的最后一个ID的地方:

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. 这两次尝试都会导致错误的值为0。

You also can retrieve the last ID of any table through sqlite_sequence. 您还可以通过sqlite_sequence检索任何表的最后一个ID。 EX- 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. ROWID以0开头,因此第一条记录的ROWID = 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM